Class: Konstruo::Mapper
- Inherits:
-
Object
- Object
- Konstruo::Mapper
- Extended by:
- T::Sig
- Defined in:
- lib/konstruo/mapper.rb
Class Attribute Summary collapse
-
.fields ⇒ Object
readonly
Returns the value of attribute fields.
Class Method Summary collapse
- .field(name, type, required: false, custom_name: nil, mapper: nil, error_message: nil) ⇒ Object
- .from_hash(hash) ⇒ Object
- .from_json(json_string) ⇒ Object
- .from_params(params) ⇒ Object
Instance Method Summary collapse
Class Attribute Details
.fields ⇒ Object (readonly)
Returns the value of attribute fields.
18 19 20 |
# File 'lib/konstruo/mapper.rb', line 18 def fields @fields end |
Class Method Details
.field(name, type, required: false, custom_name: nil, mapper: nil, error_message: nil) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/konstruo/mapper.rb', line 26 def self.field(name, type, required: false, custom_name: nil, mapper: nil, error_message: nil) # Check if the attribute is already defined attr_accessor name unless method_defined?(name) @fields ||= [] if @fields.nil? @fields << { name:, type:, required:, custom_name: custom_name || name.to_s, mapper:, error_message: } end |
.from_hash(hash) ⇒ Object
47 48 49 |
# File 'lib/konstruo/mapper.rb', line 47 def self.from_hash(hash) new.from_hash(hash) end |
.from_json(json_string) ⇒ Object
35 36 37 38 |
# File 'lib/konstruo/mapper.rb', line 35 def self.from_json(json_string) hash = JSON.parse(json_string) new.from_hash(hash) end |
.from_params(params) ⇒ Object
41 42 43 44 |
# File 'lib/konstruo/mapper.rb', line 41 def self.from_params(params) hash = params.to_unsafe_h new.from_hash(hash) end |
Instance Method Details
#from_hash(hash) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/konstruo/mapper.rb', line 52 def from_hash(hash) self.class.fields.each do |field| key = field[:custom_name] value = hash[key.to_s] || hash[key.to_sym] if value.nil? raise Konstruo::ValidationError, (field[:error_message] || "Missing required field: #{key}") if field[:required] else assign_value(field[:name], field[:type], value, field[:mapper], field[:error_message]) end end self end |