Class: PlanMyStuff::CustomFields

Inherits:
Object
  • Object
show all
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.

Instance Method Summary collapse

Constructor Details

#initialize(schema, data = {}) ⇒ CustomFields

Returns a new instance of CustomFields.

Parameters:

  • schema (Hash{Symbol => Hash})

    field definitions from config.custom_fields

  • data (Hash) (defaults to: {})

    parsed field data from metadata JSON



11
12
13
14
# File 'lib/plan_my_stuff/custom_fields.rb', line 11

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 (private)



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/plan_my_stuff/custom_fields.rb', line 50

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 Method Details

#[](key) ⇒ Object

Parameters:

  • key (Symbol, String)

Returns:

  • (Object)


20
21
22
# File 'lib/plan_my_stuff/custom_fields.rb', line 20

def [](key)
  @data[key.to_sym]
end

#[]=(key, value) ⇒ Object

Parameters:

  • key (Symbol, String)
  • value (Object)

Returns:

  • (Object)


29
30
31
# File 'lib/plan_my_stuff/custom_fields.rb', line 29

def []=(key, value)
  @data[key.to_sym] = value
end

#to_hHash

Returns:

  • (Hash)


34
35
36
# File 'lib/plan_my_stuff/custom_fields.rb', line 34

def to_h
  @data.dup
end

#to_jsonString

Returns:

  • (String)


39
40
41
# File 'lib/plan_my_stuff/custom_fields.rb', line 39

def to_json(...)
  to_h.to_json(...)
end