module Hashie::Extensions::Dash::PropertyTranslation::ClassMethods
def define_translation(from, property_name, translator)
def define_translation(from, property_name, translator) translations_hash[from][property_name] = translator end
def define_writer_for_source_property(property)
def define_writer_for_source_property(property) define_method "#{property}=" do |val| __translations[property].each do |name, with| self[name] = with.respond_to?(:call) ? with.call(val) : val end end end
def fail_self_transformation_error!(property_name)
def fail_self_transformation_error!(property_name) raise ArgumentError, "Property name (#{property_name}) and :from option must not be the same" end
def inherited(klass)
Ensures that any inheriting classes maintain their translations.
def inherited(klass) super klass.instance_variable_set(:@transforms, transforms.dup) klass.instance_variable_set(:@translations_hash, translations_hash.dup) end
def inverse_translations
def inverse_translations @inverse_translations ||= {}.tap do |translations| translations_hash.each do |(property_name, property_translations)| property_translations.each_key do |key| translations[key] = property_name end end end end
def permitted_input_keys
def permitted_input_keys @permitted_input_keys ||= properties .map { |property| inverse_translations.fetch property, property } end
def property(property_name, options = {})
* :transform_with - Specify a lambda to be used to convert value
* :with - Specify a lambda to be used to convert value.
* :from - Specify the original key name that will be write only.
returned before a value is set on the property in a new Dash.
* :default - Specify a default value for this property, to be
Defines a property on the Trash. Options are as follows:
def property(property_name, options = {}) super from = options[:from] converter = options[:with] transformer = options[:transform_with] if from fail_self_transformation_error!(property_name) if property_name == from define_translation(from, property_name, converter || transformer) define_writer_for_source_property(from) elsif valid_transformer?(transformer) transforms[property_name] = transformer end end
def transformation_exists?(name)
def transformation_exists?(name) transforms.key? name end
def transformed_property(property_name, value)
def transformed_property(property_name, value) transforms[property_name].call(value) end
def translation_exists?(name)
def translation_exists?(name) translations_hash.key? name end
def translations
def translations @translations ||= {}.tap do |translations| translations_hash.each do |(property_name, property_translations)| translations[property_name] = if property_translations.size > 1 property_translations.keys else property_translations.keys.first end end end end
def valid_transformer?(transformer)
def valid_transformer?(transformer) transformer.respond_to? :call end