Sha256: 4c64308d891a0a014c0d9b6d3ac5d88ba5dc9e5b117a1cec9e70ee0c6a2972c0

Contents?: true

Size: 1.06 KB

Versions: 13

Compression:

Stored size: 1.06 KB

Contents

class ActiveRecord::Base

  def self.relationship_with(model)
    association = reflect_on_association(model.table_name.to_sym) ||
                  reflect_on_association(model.model_name.underscore.to_sym)
    association.macro
  end

  #--
  # On a model:
  #
  #     class Post < ActiveRecord::Base
  #       STATUS = {  t("Published") => "published",
  #                   t("Pending") => "pending",
  #                   t("Draft") => "draft" }
  #     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)

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

    value = array.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

13 entries across 13 versions & 1 rubygems

Version Path
typus-3.1.0.rc17 lib/support/active_record.rb
typus-3.1.0.rc16 lib/support/active_record.rb
typus-3.1.0.rc15 lib/support/active_record.rb
typus-3.1.0.rc14 lib/support/active_record.rb
typus-3.1.0.rc13 lib/support/active_record.rb
typus-3.1.0.rc12 lib/support/active_record.rb
typus-3.1.0.rc11 lib/support/active_record.rb
typus-3.1.0.rc10 lib/support/active_record.rb
typus-3.1.0.rc9 lib/support/active_record.rb
typus-3.1.0.rc8 lib/support/active_record.rb
typus-3.1.0.rc7 lib/support/active_record.rb
typus-3.1.0.rc6 lib/support/active_record.rb
typus-3.1.0.rc5 lib/support/active_record.rb