Class: SimpleCsv::Settings

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_csv/settings.rb

Constant Summary collapse

DEFAULTS =
{ headers: true, col_sep: ',', seperator: ',',
force_quotes: true,
converters: [:all, :blank_to_nil, :null_to_nil] }.freeze
ALIASSED =
{ seperator: :col_sep, has_headers: :headers }.freeze
INVERTED_ALIASSES =
ALIASSED.to_a.map(&:reverse).to_h.freeze

Instance Method Summary collapse

Constructor Details

#initialize(**opts) ⇒ Settings

Returns a new instance of Settings.



9
10
11
# File 'lib/simple_csv/settings.rb', line 9

def initialize(**opts)
  @settings = DEFAULTS.dup.merge opts
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mtd, *args, &block) ⇒ Object



48
49
50
51
52
53
# File 'lib/simple_csv/settings.rb', line 48

def method_missing(mtd, *args, &block)
  return super unless accepted_method? mtd
  mtd = ALIASSED[mtd] if ALIASSED.key? mtd
  mtd = INVERTED_ALIASSES[mtd] if INVERTED_ALIASSES.key? mtd
  @settings[mtd]
end

Instance Method Details

#[](setting) ⇒ Object



13
14
15
# File 'lib/simple_csv/settings.rb', line 13

def [](setting)
  send setting
end

#[]=(m, val) ⇒ Object



17
18
19
20
21
22
# File 'lib/simple_csv/settings.rb', line 17

def []=(m, val)
  @settings[m] = val
  return @settings[ALIASSED[m]] = val if ALIASSED.key? m
  return @settings[INVERTED_ALIASSES[m]] = val if INVERTED_ALIASSES.key? m
  val
end

#accepted_method?(mtd) ⇒ Boolean

Returns:

  • (Boolean)


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

def accepted_method?(mtd)
  @settings.key?(mtd) || ALIASSED.key?(mtd) || INVERTED_ALIASSES.key?(mtd)
end

#any?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/simple_csv/settings.rb', line 40

def any?
  @settings && @settings.any?
end

#apply(*hashes) ⇒ Object



36
37
38
# File 'lib/simple_csv/settings.rb', line 36

def apply(*hashes)
  hashes.each { |opts| opts.each { |k, v| self[k] = v } } && @settings
end

#for_csvObject



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

def for_csv
  settings = @settings.dup

  ALIASSED.each do |opt_alias, opt|
    settings[opt] = settings.delete(opt_alias) if settings.key? opt_alias
  end

  CSV::DEFAULT_OPTIONS.each_with_object({}) do |(prop, default), csv_hash|
    csv_hash[prop] = settings.key?(prop) ? settings[prop] : default
  end
end

#respond_to_missing?(mtd, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/simple_csv/settings.rb', line 44

def respond_to_missing?(mtd, include_private = false)
  accepted_method? mtd || super
end