Sha256: 8f5ae9253cd9198f282445a471cf85b86491ace768caf7012b38f96c5f45fbf6

Contents?: true

Size: 915 Bytes

Versions: 12

Compression:

Stored size: 915 Bytes

Contents

class ActiveRecord::Base

  #--
  # 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"
  #++
  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

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

end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
typus-3.1.10 lib/support/active_record.rb
typus-3.1.9 lib/support/active_record.rb
typus-3.1.8 lib/support/active_record.rb
typus-3.1.7 lib/support/active_record.rb
typus-3.1.6 lib/support/active_record.rb
typus-3.1.5 lib/support/active_record.rb
typus-3.1.4 lib/support/active_record.rb
typus-3.1.3 lib/support/active_record.rb
typus-3.1.2 lib/support/active_record.rb
typus-3.1.1 lib/support/active_record.rb
typus-3.1.0 lib/support/active_record.rb
typus-3.1.0.rc19 lib/support/active_record.rb