Rails4.2

Active Support

Concerns

ActiveSupport::Concern
rails/concern.rb at master · rails/rails · GitHub

module XXXable
  extend ActiveSupport::Concern

  # base.class_eval(&@_included_block)
  included do
    scope :disabled, -> { where(disabled: true) }
  end

  # ClassMethods.module_eval(&class_methods_module_definition)されます
  class_methods do
    def class_method do
      ...
    end  
  end

  # base.instance_variable_set(:@_dependencies, [])
  def instance_method do
    ...
  end

  def self.self_method do
    ...
  end
end
class Hoge
  include XXXable
end
Hoge.class_method
Hoge.new.instance_method
XXXable.self_method

delegate

http://api.rubyonrails.org/classes/Module.html#method-i-delegate
rails/delegation.rb at master · rails/rails · GitHub

※最終的にはmodule_eval(method_def, file, line)されます。

class Greeter < ActiveRecord::Base
  def hello
    'hello'
  end

  def goodbye
    'goodbye'
  end
end

class Foo < ActiveRecord::Base
  belongs_to :greeter
  delegate :hello, to: :greeter
end

Foo.new.hello   # => "hello"

number_helper

ActiveSupport::NumberHelper

number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
number_to_currency(1234567890.506, locale: :fr)  # => 1 234 567 890,51 €

number_to_delimited(12345678)                    # => 12,345,678

number_to_human(500000000, precision: 5)           # => "500 Million"
number_to_human(543934, units: :distance)            # => "544 kilometers"

number_to_human_size(123)                                    # => 123 Bytes
number_to_human_size(12345)                                  # => 12.1 KB
number_to_human_size(1234567)                                # => 1.18 MB
number_to_human_size(1234567890)                             # => 1.15 GB
number_to_human_size(1234567890123)                          # => 1.12 TB

number_to_percentage(100)                                  # => 100.000%
number_to_percentage(100, precision: 0)                    # => 100%
number_to_percentage(302.24398923423, precision: 5)        # => 302.24399%

number_to_phone(5551234)                                     # => 555-1234

number_to_rounded(111.2345)                                  # => 111.235
number_to_rounded(111.2345, precision: 2)                    # => 111.23
number_to_rounded(13, precision: 5)                          # => 13.00000
number_to_rounded(389.32314, precision: 0)                   # => 389
number_to_rounded(111.2345, significant: true)               # => 111
number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
Remove all ads