Module: Cistern::Attributes::ClassMethods

Defined in:
lib/cistern/attributes.rb

Instance Method Summary collapse

Instance Method Details

#aliasesObject



40
41
42
# File 'lib/cistern/attributes.rb', line 40

def aliases
  @aliases ||= Hash.new { |h, k| h[k] = [] }
end

#attribute(name, options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cistern/attributes.rb', line 48

def attribute(name, options = {})
  name_sym = name.to_sym

  if attributes.key?(name_sym)
    fail(ArgumentError, "#{self.name} attribute[#{name_sym}] specified more than once")
  end

  add_coverage(options)

  normalize_options(options)

  attributes[name_sym] = options

  define_attribute_reader(name_sym, options) unless options[:reader] == false
  define_attribute_writer(name_sym, options) unless options[:writer] == false

  name_sym
end

#attributesObject



44
45
46
# File 'lib/cistern/attributes.rb', line 44

def attributes
  @attributes ||= parent_attributes || {}
end

#default_parserObject



36
37
38
# File 'lib/cistern/attributes.rb', line 36

def default_parser
  @default_parser ||= ->(v, _opts) { v }
end

#identity(*args) ⇒ Object



67
68
69
# File 'lib/cistern/attributes.rb', line 67

def identity(*args)
  args.any? ? @identity = attribute(*args) : (@identity ||= parent_identity)
end

#ignore_attributes(*args) ⇒ Object



71
72
73
# File 'lib/cistern/attributes.rb', line 71

def ignore_attributes(*args)
  @ignored_attributes = args
end

#ignored_attributesObject



75
76
77
# File 'lib/cistern/attributes.rb', line 75

def ignored_attributes
  @ignored_attributes ||= []
end

#parsersObject



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/cistern/attributes.rb', line 8

def parsers
  @parsers ||= {
    array:   ->(v, _) { [*v] },
    boolean: ->(v, _) { TRUTHY.include?(v.to_s.downcase) },
    date:    ->(v, _) { v.is_a?(Date) ? v : v && Date.parse(v.to_s) },
    float:   ->(v, _) { v && v.to_f },
    integer: ->(v, _) { v && v.to_i },
    string:  ->(v, _) { v && v.to_s },
    time:    ->(v, _) { v.is_a?(Time) ? v : v && Time.parse(v.to_s) },
  }
end

#squasher(tree, path) ⇒ Object



20
21
22
# File 'lib/cistern/attributes.rb', line 20

def squasher(tree, path)
  tree.is_a?(::Hash) ? squasher(tree[path.shift], path) : tree
end

#transformsObject



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/cistern/attributes.rb', line 24

def transforms
  @transforms ||= {
    squash: proc do |_, _v, options|
      v      = Cistern::Hash.stringify_keys(_v)
      squash = options[:squash]

      v.is_a?(::Hash) ? squasher(v, squash.dup) : v
    end,
    none: ->(_, v, _) { v }
  }
end