Class: Whiteprint::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/whiteprint/attributes.rb

Instance Method Summary collapse

Constructor Details

#initialize(persisted: nil, model: nil, **options) ⇒ Attribute

Returns a new instance of Attribute.



3
4
5
6
7
# File 'lib/whiteprint/attributes.rb', line 3

def initialize(persisted: nil, model: nil, **options)
  @model     = model
  @options   = options
  @persisted = persisted
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/whiteprint/attributes.rb', line 65

def method_missing(name)
  if name.to_s.starts_with?('meta_')
    self[name.to_s.remove(/^meta_/)]
  else
    self[name]
  end
end

Instance Method Details

#==(other) ⇒ Object



9
10
11
# File 'lib/whiteprint/attributes.rb', line 9

def ==(other)
  to_h == other.to_h
end

#[](name) ⇒ Object



47
48
49
# File 'lib/whiteprint/attributes.rb', line 47

def [](name)
  @options[name.to_sym]
end

#for_meta(instance) ⇒ Object



36
37
38
39
40
# File 'lib/whiteprint/attributes.rb', line 36

def for_meta(instance)
  ::Whiteprint.config.meta_attribute_options.map do |option|
    {option => send("meta_#{option}", instance)}
  end.inject(&:merge).compact
end

#for_persisted(**config) ⇒ Object



42
43
44
45
# File 'lib/whiteprint/attributes.rb', line 42

def for_persisted(**config)
  return merge(config) if @persisted
  self.class.new(persisted: true, name: @options[:name], type: @options[:type], options: persisted_options, **config)
end

#has?(*keys, **conditions) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
# File 'lib/whiteprint/attributes.rb', line 13

def has?(*keys, **conditions)
  keys.none? do |key|
    @options.values_at(*key).compact.empty?
  end && conditions.all? do |key, value|
    [*@options[key]] & [*value] != []
  end
end

#merge(options) ⇒ Object



32
33
34
# File 'lib/whiteprint/attributes.rb', line 32

def merge(options)
  self.class.new(persisted: @persisted, **@options, **options)
end

#meta_enum(instance) ⇒ Object



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

def meta_enum(instance)
  _enum = if enum.is_a?(Symbol)
            instance.send(enum)
          else
            enum
          end

  return _enum if _enum.is_a?(Hash)

  _enum.map do |value|
    {value => value}
  end.inject(&:merge)
end

#persisted_optionsObject



21
22
23
24
25
26
# File 'lib/whiteprint/attributes.rb', line 21

def persisted_options
  @options.select do |key, value|
    Whiteprint.config.persisted_attribute_options.keys.include?(key) &&
    !(key == :default && value.is_a?(Symbol))
  end
end

#to_hObject



28
29
30
# File 'lib/whiteprint/attributes.rb', line 28

def to_h
  @options
end