Sha256: 6f507c04d6b0c1efdd71f9d67a70438816151cfdc5d17a2dad12694087cafd23

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

module AssignableValues
  module ActiveRecord
    module Restriction
      class ScalarAttribute < Base

        def initialize(*args)
          super
          define_humanized_method
        end

        def humanize_string_value(value)
          if value.present?
            if @hardcoded_humanizations
              @hardcoded_humanizations[value]
            else
              dictionary_key = "assignable_values.#{model.name.underscore}.#{property}.#{value}"
              I18n.t(dictionary_key, :default => value.humanize)
            end
          end
        end

        private

        def parse_values(values)
          if values.is_a?(Hash)
            @hardcoded_humanizations = values
            values = values.keys
          else
            super
          end
        end

        def define_humanized_method
          restriction = self
          enhance_model do
            define_method "humanized_#{restriction.property}" do
              value = send(restriction.property)
              restriction.humanize_string_value(value)
            end
          end
        end

        def decorate_values(values)
          restriction = self
          values.collect do |value|
            if value.is_a?(String)
              value = value.dup
              value.singleton_class.send(:define_method, :humanized) do
                restriction.humanize_string_value(value)
              end
            end
            value
          end
        end

        def previously_saved_value(record)
          record.send("#{property}_was")
        end

      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
assignable_values-0.2.1 lib/assignable_values/active_record/restriction/scalar_attribute.rb
assignable_values-0.2.0 lib/assignable_values/active_record/restriction/scalar_attribute.rb