arel_table order by

equivalent Oct 5, 2015

More objected way how to achieve ORDOR BY .... DESC is like this :

class User < ActiveRecord::Base
  has_many :status_changes

  def latest_status_change
    status_changes
     .order(StatusChange.arel_table['created_at'].desc)
     .first
  end
end

class Stat...

Add method to instacne eval

sselvamani22 Aug 18, 2015

We can add method to instance by using instance_eval.

==== Code example string = "String" string.instance_eval do def new_method self.reverse end end

=== Output

irb(main):033:0> string.new_method => "gnirtS"

Also takes a block

rjspotter Jul 31, 2015

You can define methods within a block

User = Struct.new(:first_name, :last_name) do
def full_name
  "#{first_name} #{last_name}"
end
end

user = User.new('Simon', 'Templar') # => #<struct User first_name="Simon", last_name="Templar">
user.full_name # => "Simon Templar"

Important note!

sandyjoins Jul 13, 2015

Special cases:

==== Code example
"Test".byteslice(1, 3) => "est" #both limits inclusive

"Test".byteslice(0, 3) => "Tes" #upper limit exclusive

"Test".byteslice(0..3) => "Test" # Both limits inclusive