module HashCast::Caster::ClassMethods

Constants

ALLOWED_OPTIONS

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/hashcast/caster.rb, line 92
def attributes(&block)
  raise ArgumentError, "You should provide block" unless block_given?

  attributes = HashCast::AttributesParser.parse(&block)
  self.instance_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/hashcast/caster.rb, line 102
def cast(hash, options = {})
  check_attributes_defined!
  check_hash_given!(hash)
  check_options!(options)
  options = set_default_options(options)

  attributes_caster = HashCast::AttributesCaster.new(instance_variable_get(:@attributes), options)
  attributes_caster.cast(hash)
end

Private Instance Methods

check_attributes_defined!() click to toggle source
# File lib/hashcast/caster.rb, line 114
def check_attributes_defined!
  unless instance_variable_defined?(:@attributes)
    raise HashCast::Errors::ArgumentError, "Attributes block should be defined"
  end
end
check_hash_given!(hash) click to toggle source
# File lib/hashcast/caster.rb, line 132
def check_hash_given!(hash)
  unless hash.is_a?(Hash)
    raise HashCast::Errors::ArgumentError, "Hash should be given"
  end
end
check_options!(options) click to toggle source
# File lib/hashcast/caster.rb, line 120
def check_options!(options)
  unless options.is_a?(Hash)
    raise HashCast::Errors::ArgumentError, "Options should be a hash"
  end
  if options[:input_keys] && !ALLOWED_OPTIONS.include?(options[:input_keys])
    raise HashCast::Errors::ArgumentError, "input_keys should be :string or :symbol"
  end
  if options[:output_keys] && !ALLOWED_OPTIONS.include?(options[:output_keys])
    raise HashCast::Errors::ArgumentError, "output_keys should be :string or :symbol"
  end
end
set_default_options(options) click to toggle source
# File lib/hashcast/caster.rb, line 138
def set_default_options(options)
  options[:input_keys]  ||= HashCast.config.input_keys
  options[:output_keys] ||= HashCast.config.output_keys
  options
end