Class: RiceBubble::Attributes::Base

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

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Base

Returns a new instance of Base.



4
5
6
# File 'lib/rice_bubble/attributes/base.rb', line 4

def initialize(&block)
  @fetcher = block
end

Instance Method Details

#call(value, path: '') ⇒ Object



26
27
28
29
30
31
32
# File 'lib/rice_bubble/attributes/base.rb', line 26

def call(value, path: '')
  if valid?(value)
    value
  else
    validation_error(value:, path:)
  end
end

#descriptionObject



38
39
40
41
42
43
44
# File 'lib/rice_bubble/attributes/base.rb', line 38

def description
  soft_name = self.class.name.split('::').last
    .gsub(/([a-z])([A-Z])/, '\1 \2')
    .downcase
  article = soft_name.start_with?(/[aeiou]/) ? 'an' : 'a'
  "#{article} #{soft_name}"
end

#fetch(object, name) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/rice_bubble/attributes/base.rb', line 8

def fetch(object, name)
  if @fetcher
    @fetcher.call(object, name)
  elsif object.respond_to?(name)
    object.public_send(name)
  else
    object[name] || object[name.to_s]
  end
end

#optionalObject



34
35
36
# File 'lib/rice_bubble/attributes/base.rb', line 34

def optional
  Optional.new(self)
end

#valid?(value) ⇒ Boolean

Returns:



18
19
20
# File 'lib/rice_bubble/attributes/base.rb', line 18

def valid?(value)
  valid_types.any? { |t| value.is_a?(t) }
end

#valid_typesObject



22
23
24
# File 'lib/rice_bubble/attributes/base.rb', line 22

def valid_types
  [::Object]
end