Class: Somatics::Generators::SettingsGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
Rails::Generators::Migration
Defined in:
lib/generators/somatics/settings/settings_generator.rb

Instance Method Summary collapse

Instance Method Details

#add_name_indexObject



15
16
17
18
19
# File 'lib/generators/somatics/settings/settings_generator.rb', line 15

def add_name_index
  inject_into_file Dir.glob("db/migrate/[0-9]*_*.rb").last, :before => "end\n\n  def self.down" do
    "add_index :settings, :name, :unique => true\n"
  end
end

#generate_modelObject



11
12
13
# File 'lib/generators/somatics/settings/settings_generator.rb', line 11

def generate_model
  invoke "somatics:scaffold", ["settings" , "name:string", "field_type:string", "value:text", "category:string", "description:text", "mce_editable:boolean"], {:scaffold_controller => "settings_controller"}
end

#inject_model_validatorsObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/generators/somatics/settings/settings_generator.rb', line 21

def inject_model_validators
  inject_into_class 'app/models/setting.rb', 'Setting' do 
    <<-RUBY
  GENERAL = 'General'
  CATEGORIES = [GENERAL]
  FIELD_TYPES = ['integer', 'string', 'float', 'text', 'boolean']

  attr_protected :name, :field_type, :description, :category, :mce_editable

  validates_presence_of :name
  validates_uniqueness_of :name
  validates_presence_of :field_type
  validates_inclusion_of :field_type, :in => FIELD_TYPES
  validates_presence_of :category
  validates_inclusion_of :category, :in => CATEGORIES
  validates_presence_of :value, :allow_blank => true
  validates_numericality_of :value, :if => Proc.new {|setting| ['integer', 'float'].include?(setting.field_type) }

  def self.[](name)
    raise SettingNotFound unless setting = Setting.find_by_name(name)
    setting.parsed_value
  end

  def self.[]=(name, value)
    raise SettingNotFound unless setting = Setting.find_by_name(name)
    setting.update_attribute(:value, value)
  end

  def parsed_value
    case self.field_type
    when 'integer'
self.value.to_i
    when 'float'
self.value.to_f
    when 'boolean'
self.value == '1'
    else
self.value
    end
  end

  def input_field(form)
    options = {}
    input_field_type = case self.field_type
    when 'integer', 'string', 'float'
'text_field'
    when 'text'
options[:class] = 'mceEditor'
'text_area'
    when 'boolean'
'check_box'
    else
'text_field'
    end
    form.send(input_field_type, :value, options)
  end

  class SettingNotFound < Exception; end
  
    RUBY
  end rescue nil

end