Module: Cistern::Attributes

Defined in:
lib/cistern/attributes.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.default_parserObject



46
47
48
# File 'lib/cistern/attributes.rb', line 46

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

.parsersObject



2
3
4
5
6
7
8
9
10
11
# File 'lib/cistern/attributes.rb', line 2

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

.transformsObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/cistern/attributes.rb', line 13

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

      if v.is_a?(::Hash) && squash.is_a?(Array)
        travel = lambda do |tree, path|
          if tree.is_a?(::Hash)
            travel.call(tree[path.shift], path)
          else
            tree
          end
        end

        travel.call(v, squash.dup)
      elsif v.is_a?(::Hash)
        squash_s = squash.to_s

        if v.key?(key = squash_s.to_sym)
          v[key]
        elsif v.key?(squash_s)
          v[squash_s]
        else
          v
        end
      else v
      end
    end,
    none: ->(_, v, _) { v }
  }
end