Class: PlanMyStuff::CustomFields
- Inherits:
-
Object
- Object
- PlanMyStuff::CustomFields
show all
- Includes:
- ActiveModel::Validations
- Defined in:
- lib/plan_my_stuff/custom_fields.rb
Overview
Dynamic accessor object for app-defined custom fields stored in metadata. Backed by the config.custom_fields schema, provides both hash-style and method-style access to field values.
Includes ActiveModel::Validations for type checking, required field enforcement, and unknown field detection.
Constant Summary
collapse
- TYPE_MAP =
{
string: [String],
integer: [Integer],
boolean: [TrueClass, FalseClass],
array: [Array],
hash: [Hash],
}.freeze
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(schema, data = {}) ⇒ CustomFields
Returns a new instance of CustomFields.
31
32
33
34
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 31
def initialize(schema, data = {})
@schema = schema || {}
@data = (data || {}).transform_keys(&:to_sym)
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object
Dynamic reader/writer access to custom field values. Only resolves field names that appear in the schema or already have a value in @data; unknown names fall through to super (raising NoMethodError).
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 82
def method_missing(method_name, *args)
name = method_name.to_s
if name.end_with?('=')
key = name.delete_suffix('=').to_sym
if @schema.key?(key) || @data.key?(key)
return @data[key] = args.first
end
elsif @schema.key?(method_name) || @data.key?(method_name)
return @data[method_name]
end
super
end
|
Instance Attribute Details
#schema ⇒ Hash{Symbol => Hash}
26
27
28
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 26
def schema
@schema
end
|
Instance Method Details
#[](key) ⇒ Object
40
41
42
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 40
def [](key)
@data[key.to_sym]
end
|
#[]=(key, value) ⇒ Object
49
50
51
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 49
def []=(key, value)
@data[key.to_sym] = value
end
|
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
68
69
70
71
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 68
def respond_to_missing?(method_name, include_private = false)
key = method_name.to_s.delete_suffix('=').to_sym
@schema.key?(key) || @data.key?(key) || super
end
|
#to_h ⇒ Hash
54
55
56
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 54
def to_h
@data.dup
end
|
#to_json ⇒ String
59
60
61
|
# File 'lib/plan_my_stuff/custom_fields.rb', line 59
def to_json(...)
to_h.to_json(...)
end
|