Sonntag, 27. Juli 2014

Merge your ActiveRecord scopes!

ActiveRecord scopes help to abstract out several SQL fragments in a elegant object oriented manner. Since they are combineable and reuseable, they help to maintain database related code.
The original ActiveRecord models:
class Food < ActiveRecord::Base
  has_and_belongs_to_many :ingredients
  scope :preservative, joins(:ingredients).where("ingredients.preservative" => true)
end

class Ingredient < ActiveRecord::Base
end
are tied together via a 1:n relationship. Furthermore there is scope, which shrinks the amount of foods having preservative ingredients. It has a name :preservative and receives a join and a condition (for more detailed explanation of ActiveRecord scopes go read: Scope the model!).
But it suffers knowing about the internal table structure of a different model, which increases the coupling between both classes.
That issue can be solved by merging scopes of different model classes:
class Food < ActiveRecord::Base
  has_and_belongs_to_many :ingredients
  scope :preservative, joins(:ingredients).merge(Ingredient.preservative)
end

class Ingredient < ActiveRecord::Base
  scope :preservative, where("#{table_name}.preservative" => true)
end
Now the Ingredient model takes the responsibility for its scope, where it belongs (please note that using ActiveRecord::ModelSchema::ClassMethods#table_name removes the knowledge about the table name in the scope itself).
The interesting part is the scope Food#preservative. Besides still joining the other model via the association, it uses ActiveRecord::SpawnMethods#merge for merging the scope Ingredient#preservative into the scope Food#preservative.
The usage:
preservative_foods = Food.preservative
Further articles of interest:

Supported by Ruby 2.1.1 and Ruby on Rails 3.2.17

Sonntag, 20. Juli 2014

Use a font for form check boxes! ... CSS based.

Native form check boxes suffer some disadvantages. They:
  1. are not cross browser consistent (Safari, Chrome, Opera or Firefox)
  2. are not scaleable
  3. are not fully styleable (and therefore may not fit to the look and feel of the page)
Native web form check boxes could look like:
The check boxes above are built on:
with some CSS:
div.checkboxes input[type=checkbox]{
  float: left;
  margin-right: 1em;
}
div.checkboxes label{
  display: block;
  margin: 0.5em;
}
Compare the native look and feel with the CSS font based only solution:
Since the check box font solution is based on CSS styles only, the HTML structure is still the same (except the input elements have the additional CSS class 'hidden'), but with some additional CSS:
@font-face {
  font-family: 'FontAwesome';
  src: url(/assets/fontawesome-webfont.eot?v=4.1.0);
  src: url(/assets/fontawesome-webfont.eot?#iefix&v=4.1.0) format("embedded-opentype"), 
    url(/assets/fontawesome-webfont.woff?v=4.1.0) format("woff"),   
    url(/assets/fontawesome-webfont.ttf?v=4.1.0) format("truetype"), 
    url(/assets/fontawesome-webfont.svg?v=4.1.0#fontawesomeregular) format("svg");
  font-weight: normal;
  font-style: normal;
} 
.hidden{
  display: none;
}
div.checkboxes input[type=checkbox].hidden + label:before{
  font-family: FontAwesome;
  font-size: 1.5em;
  font-style: normal;  
  cursor: pointer;
}
div.checkboxes input[type=checkbox].hidden + label:before{
  content: "\f096";
  margin-right: 1em;
  position: relative;
  top: 0.2em;
}
div.checkboxes input[type=checkbox].hidden:checked + label:before{
  content: '\f046';
  color: #A00000;
}
div.checkboxes input[type=checkbox].hidden:hover + label:before{
  font-size: 2em;
}
div.checkboxes input[type=checkbox].hidden:active + label:before{
  text-shadow: 0px 0px 5px #666;
}
In the example the awesome font 'Awesome' was used.
It is important to include the font into the page with '@font-face'. That forces the clients to download the font once (after the font was downloaded the clients are considered to hold it in their cache).
Please note, that the check box inputs are hidden, but still existing.
Furthermore the font content is styled before the label by using the pseudo class ':before'. In combination with the state of the check box by using the CSS3 pseudo class ':checked' the content is overridden.
All following styles are just for improving the user experience, although this is pretty subjective and can vary depending on the use case.
The technique can be applied to other form controls as well, like radio buttons.

Firefox 21+, Chrome 21+, Safari 5.1+, Opera 12.1+, IE 9+, Android browser 2.3+, iOS Safari 6.0+, Opera min 5.0+

Sonntag, 13. Juli 2014

Differ between Proc and lambda in Ruby!

First of all there is no difference between a Proc (read Do the Proc! ... a Ruby closure) and a lambda (read Have a lambda! ... a Ruby closure) in Ruby, technically spoken. Both are Proc objects:
Proc.new {}
=> #<Proc:0x000000029642c0@(irb):1>
lambda {}
=> #<Proc:0x000000029642c0@(irb):2 (lambda)>
but with a different flavor (please note the second object stringification).
Well, but that's not the only difference (otherwise having 2 equal closure types in Ruby would not make any sense).
The differences are:
  1. lambda check the number of arguments and Procs do not.
  2. Proc and lambda treat return differently
A lambda checks the number of arguments:
lamda = lambda { |language| puts language }
lamda.call 'Ruby'          # prints Ruby
lamda.call                 # ArgumentError: wrong number of arguments (0 for 1)
lamda.call 'Ruby', 'Java'  # ArgumentError: wrong number of arguments (2 for 1)
unlike the Proc:
proc = Proc.new { |language| puts language }
proc.call 'Ruby'          # prints Ruby
proc.call                 # prints nothing
proc.call 'Ruby', 'Java'  # prints Ruby, but ignores Java
In terms of the second difference, a lambda returning something explicitly, will not force the environment (of the closure) to return either:
def lambda_environment
  lamda = lambda { return }
  lamda.call
  puts 'Ruby'
end
lambda_environment # prints Ruby
The lambda returns into its environment and let it end its processing.
But the Proc does not:
def proc_environment
  proc = Proc.new { return }
  proc.call
  puts 'Ruby'
end
proc_environment # does not print anything
The Proc forces its environment to return immediately. Further articles of interest:

Supported by Ruby 2.1.1

Sonntag, 6. Juli 2014

Have a lambda! ... a Ruby closure

First of all a lambda is one of the Ruby ways of implementing a closure. A closure makes a copy of its lexical environment, extended with the argument values bound to the function's formal parameters. Thus the body of the function in this new environment can be evaluated.
Since in Ruby everything is an object, a lambda is also one. It is just a Proc object, but with a different flavor:
lambda { return 'lambda' }
=> #
Please note the "(lambda)" in the stringified object.
In an example the original code:
class Array
  def aggregate
    self.inject(0) { |result, number| result += yield(number) }
  end
end
can be used like:
numbers = [1, 2, 3]
numbers.aggregate { |number| number ** 2 }
=> 14
If the passed block logic has to be used over and over again, a storing that logic into a variable solves the problem of duplicating the code:
squaring_lambda = lambda { |number| number ** 2 }
=> #
The Array#aggregate has to be made ready for passing a lambda by adding the new parameter and sending the Proc#call message:
class Array
  def aggregate block
    self.inject(0) { |result, number| result += block.call(number) }
  end
end
Using the instantiated lambda:
numbers = [1, 2, 3]
numbers.aggregate squaring_lambda
=> 14
and this lambda (which is a Proc object) can be reused as many as ...
The domain of a lambda is the same as the Proc's domain:
  1. wherever a block is required
  2. the block logic has to be duplicated (reused)

Further articles of interest:

Supported by Ruby 2.1.1