Class: ActiveRecord::Base

Inherits:
Object show all
Defined in:
lib/support/active_record.rb

Instance Method Summary collapse

Instance Method Details

#mapping(attribute) ⇒ Object

– On a model:

class Post < ActiveRecord::Base
  def self.statuses
    { t("Published") => "published",
      t("Pending") => "pending",
      t("Draft") => "draft" }
  end
end

>> Post.first.status
=> "published"
>> Post.first.mapping(:status)
=> "Published"
>> I18n.locale = :es
=> :es
>> Post.first.mapping(:status)
=> "Publicado"

++



23
24
25
26
27
28
29
30
31
# File 'lib/support/active_record.rb', line 23

def mapping(attribute)
  klass = self.class
  values = klass.send(attribute.to_s.pluralize)

  array = values.first.is_a?(Array) ? values : values.map { |i| [i, i] }

  value = array.to_a.rassoc(send(attribute))
  value ? value.first : send(attribute)
end

#to_labelObject



33
34
35
36
37
38
39
# File 'lib/support/active_record.rb', line 33

def to_label
  if respond_to?(:name) && send(:name).present?
    send(:name)
  else
    [self.class, id].join("#")
  end
end