module Morf::Caster::ClassMethods
Public Instance Methods
attributes(&block)
click to toggle source
Defines casting rules @example
attributes do string :first_name string :last_name integer :age, optional: true end
# File lib/morf/caster.rb, line 91 def attributes(&block) raise ArgumentError, "You should provide block" unless block_given? attributes = Morf::AttributesParser.parse(&block) self.class_variable_set(:@@attributes, attributes) end
cast(hash, options = {})
click to toggle source
Performs casting @param hash [Hash] hash for casting @param options [Hash] options, input_keys: :string, output_key: :symbol
# File lib/morf/caster.rb, line 101 def cast(hash, options = {}) check_attributes_defined! check_hash_given!(hash) check_options!(options) set_default_options(options) attributes_caster = Morf::AttributesCaster.new(class_variable_get(:@@attributes), options) attributes_caster.cast(hash) end
Private Instance Methods
check_attributes_defined!()
click to toggle source
# File lib/morf/caster.rb, line 113 def check_attributes_defined! unless class_variable_defined?(:@@attributes) raise Morf::Errors::ArgumentError, "Attributes block should be defined" end end
check_hash_given!(hash)
click to toggle source
# File lib/morf/caster.rb, line 131 def check_hash_given!(hash) unless hash.is_a?(Hash) raise Morf::Errors::ArgumentError, "Hash should be given" end end
check_options!(options)
click to toggle source
# File lib/morf/caster.rb, line 119 def check_options!(options) unless options.is_a?(Hash) raise Morf::Errors::ArgumentError, "Options should be a hash" end if options[:input_keys] && ![:string, :symbol].include?(options[:input_keys]) raise Morf::Errors::ArgumentError, "input_keys should be :string or :symbol" end if options[:output_keys] && ![:string, :symbol].include?(options[:output_keys]) raise Morf::Errors::ArgumentError, "output_keys should be :string or :symbol" end end
set_default_options(options)
click to toggle source
# File lib/morf/caster.rb, line 137 def set_default_options(options) options[:input_keys] ||= Morf.config.input_keys options[:output_keys] ||= Morf.config.output_keys end