Class: Keepassx::Fieldable

Inherits:
Object
  • Object
show all
Defined in:
lib/keepassx/fieldable.rb

Direct Known Subclasses

Entry, Group

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload) ⇒ Fieldable

Returns a new instance of Fieldable.



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

def initialize(payload)
  @fields = []

  if payload.is_a?(StringIO)
    @fields = decode_payload(payload)
  elsif payload.is_a?(Hash)
    yield
  else
    raise ArgumentError, "Expected StringIO or Hash, got #{payload.class}"
  end
end

Class Attribute Details

.field_descriptorObject (readonly)

Returns the value of attribute field_descriptor.



23
24
25
# File 'lib/keepassx/fieldable.rb', line 23

def field_descriptor
  @field_descriptor
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



6
7
8
# File 'lib/keepassx/fieldable.rb', line 6

def fields
  @fields
end

Class Method Details

.create_fieldable_methods(methods) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/keepassx/fieldable.rb', line 31

def create_fieldable_methods(methods)
  methods.each do |_, method, _|
    define_method method do
      get method
    end

    define_method "#{method}=" do |v|
      set method, v
    end
  end
end

.fieldsObject

Return the list of fields’ names



45
46
47
# File 'lib/keepassx/fieldable.rb', line 45

def fields
  @fields ||= field_descriptor.fields_description.map { |_, name, _| name }
end

.set_field_descriptor(klass) ⇒ Object



25
26
27
28
# File 'lib/keepassx/fieldable.rb', line 25

def set_field_descriptor(klass)
  @field_descriptor = klass
  create_fieldable_methods(klass.fields_description)
end

Instance Method Details

#encodeObject



71
72
73
74
75
76
77
# File 'lib/keepassx/fieldable.rb', line 71

def encode
  buffer = +''
  fields.each do |field|
    buffer << field.encode
  end
  buffer
end

#inspectObject



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/keepassx/fieldable.rb', line 80

def inspect
  output = []
  default_fields.each_key do |field_name|
    if field_name == :password
      output << 'password=[FILTERED]'
    else
      output << "#{field_name}=#{send(field_name)}" unless field_name == :terminator
    end
  end
  "<#{self.class} #{output.join(', ')}>"
end

#lengthObject



52
53
54
# File 'lib/keepassx/fieldable.rb', line 52

def length
  fields.map(&:length).reduce(&:+)
end

#to_hash(opts = {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/keepassx/fieldable.rb', line 57

def to_hash(opts = {})
  skip_date = opts.fetch(:skip_date, false)

  result = {}
  fields.each do |field|
    next if excluded_field?(field.name)
    next if date_field?(field.name) && skip_date

    result[field.name] = field.data
  end
  result
end