Module: UserPrefs

Defined in:
lib/user_prefs.rb,
lib/user_prefs/version.rb,
lib/user_prefs/class_methods.rb,
lib/user_prefs/macro_methods.rb

Defined Under Namespace

Modules: ClassMethods, MacroMethods Classes: ColumnError, PreferenceError

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



59
60
61
62
63
64
65
# File 'lib/user_prefs.rb', line 59

def method_missing(method_name, *args, &block)
  if (match_data = method_name.to_s.match(/(\w+)_pref(=|\?)?/))
    preference_method(match_data[1], match_data[2], args.first)
  else
    super
  end
end

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/user_prefs.rb', line 10

def included(base)
  validate_column_and_type(base) unless RUBY_ENGINE == :opal

  base.class_eval do
    class_attribute :defined_prefs, :default_prefs

    self.defined_prefs ||= []
    self.default_prefs ||= {}

    serialize(prefs_column.to_sym, RUBY_ENGINE == 'opal' ? Hash : HashWithIndifferentAccess)
  end

  base.extend(ClassMethods)
end

Instance Method Details

#add_pref(key, value) ⇒ Object



51
52
53
# File 'lib/user_prefs.rb', line 51

def add_pref(key, value)
  self.prefs_attr = prefs_attr.merge(Hash[key, value])
end

#delete_pref(key) ⇒ Object



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

def delete_pref(key)
  self.prefs_attr = prefs_attr.reject { |k, _v| k.to_s == key.to_s }
end

#prefsObject



47
48
49
# File 'lib/user_prefs.rb', line 47

def prefs
  prefs_attr.merge(Hash[self.class.defined_prefs.map { |k| [k, send("#{k}_pref")] }])
end

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

Returns:

  • (Boolean)


67
68
69
# File 'lib/user_prefs.rb', line 67

def respond_to_missing?(method_name, include_private = false)
  method_name =~ /(\w+)_pref(=|\?)?/ || super
end