Module: Usable::Persistence::InstanceMethods

Defined in:
lib/usable/persistence.rb

Overview

Automatically copied over by usable

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Accessor to read and write default ActiveRecord objects When assigning a config, a reference to it is saved to tmp/<mod_name>.yml and loaded in subsequent console sessions



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/usable/persistence.rb', line 24

def method_missing(name, *args, &block)
  if block
    usables.public_send(name, &block)
  elsif name.to_s.end_with?('=') && args.length == 1
    _save name.to_s.tr('=', '').to_sym, args.pop
  elsif usables[name]
    usables[name]
  elsif _config[name]
    usables[name] = if _config[name].is_a?(Hash)
                      _config[name].fetch(:class).constantize.find(_config[name].fetch(:id))
                    else
                      _config[name]
                    end
  else
    usables.public_send(name) || super
  end
end

Instance Method Details

#_configObject



77
78
79
# File 'lib/usable/persistence.rb', line 77

def _config
  @_config ||= YAML.load_file(_config_file) || {}
end

#_config_fileObject



68
69
70
71
72
73
74
75
# File 'lib/usable/persistence.rb', line 68

def _config_file
  return @_config_file if @_config_file
  FileUtils.mkdir_p(usables.dir) unless File.directory?(usables.dir)
  filename = self.class.name ? self.class.name.downcase.gsub('::', '_') : 'usable'
  @_config_file = File.join(usables.dir, "#{filename}.yml")
  FileUtils.touch(@_config_file) unless File.exists?(@_config_file)
  @_config_file
end

#_save(key, val = nil) ⇒ Object

Private



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/usable/persistence.rb', line 56

def _save(key, val = nil)
  if val.nil?
    _config.delete(key)
  elsif val.respond_to?(:persisted?) && val.persisted?
    _config[key] = { class: val.class.name, id: val.id }
  else
    _config[key] = val
  end
  File.open(_config_file, 'wb') { |f| f.puts _config.to_yaml }
  usables[key] = val
end

#has?(setting) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
# File 'lib/usable/persistence.rb', line 42

def has?(setting)
  !!send(setting)
rescue NoMethodError => e
  if e.message.include?("method `#{setting}'")
    false
  else
    raise
  end
end