Class: SelfData

Inherits:
Object
  • Object
show all
Defined in:
lib/self_data.rb,
lib/self_data/errors.rb,
lib/self_data/version.rb

Defined Under Namespace

Classes: ConversionError, ConverterNotFound, NoDataFound

Constant Summary collapse

Error =
Class.new(StandardError)
VERSION =
"1.2.0"

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = caller_file) ⇒ SelfData

Returns a new instance of SelfData.



37
38
39
# File 'lib/self_data.rb', line 37

def initialize(file = caller_file)
  @file = file
end

Class Attribute Details

.default_formatsObject

Returns the value of attribute default_formats.



8
9
10
# File 'lib/self_data.rb', line 8

def default_formats
  @default_formats
end

.default_optionsObject

Returns the value of attribute default_options.



8
9
10
# File 'lib/self_data.rb', line 8

def default_options
  @default_options
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



35
36
37
# File 'lib/self_data.rb', line 35

def file
  @file
end

Class Method Details

.add_converter(name, block) ⇒ Object



30
31
32
# File 'lib/self_data.rb', line 30

def add_converter(name, block)
  converters[name] = block
end

.add_filter(&block) ⇒ Object



22
23
24
# File 'lib/self_data.rb', line 22

def add_filter(&block)
  filters << block
end

.convertersObject



26
27
28
# File 'lib/self_data.rb', line 26

def converters
  @converters ||= {}
end

.filtersObject



18
19
20
# File 'lib/self_data.rb', line 18

def filters
  @filters ||= []
end

.load(*args) ⇒ Object



14
15
16
# File 'lib/self_data.rb', line 14

def load(*args)
  new.load(*args)
end

.read(*args) ⇒ Object



10
11
12
# File 'lib/self_data.rb', line 10

def read(*args)
  new.read(*args)
end

Instance Method Details

#load(*formats, **options) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/self_data.rb', line 41

def load(*formats, **options)
  formats = self.class.default_formats if formats.empty?
  options = self.class.default_options if options.empty?

  formats.reduce(read) do |data, format|
    raise ConverterNotFound, format unless self.class.converters[format]
    begin
      self.class.converters[format].call(data, options)
    rescue => e
      raise ConversionError.new(format, e)
    end
  end
end

#readObject



55
56
57
# File 'lib/self_data.rb', line 55

def read
  IO.read(file).scan(/\n__END__\n(.*)/m).flatten.first or raise NoDataFound, file
end