rails-settings-cached 0.4.1 → 0.6.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 6bd842dbc504791a77630162468aa6e478a995c2
4
- data.tar.gz: 5dcfb862ea79ee47eec0dd6316dfad8b3d1ff811
3
+ metadata.gz: 77ee4761ccc2fa3dcd3b594e8de0878dfff7737c
4
+ data.tar.gz: 453fbd403e16fd91823f64853c209e9742c20ef2
5
5
  SHA512:
6
- metadata.gz: cd476936667b371251f5fb6b66a3a1dabdf5e99b6808171ecfdd0baa38bca03df6e6ed9475ed7a488626795952076a87d42923b174a13da57e4e1d24bb7c5e95
7
- data.tar.gz: 8f093f58bf66a5939d57c6d412a7b9ce742b95f0de4d2f34ea1c0db53fc720df7aa23761964162b0a6d9ff1344630afa405ad9c348bc266a18c0a8ef4008d560
6
+ metadata.gz: 498d13784837ecb3ad5b9ee48ff73a9ca19acb0086a950179c34e8c130056aa02af31ef3acab41a0e67eb715d41462b64cdec206bdeb35222b7562f3354c4de2
7
+ data.tar.gz: 4a054dedbd4d73dcdb571e658e9ecc82dcb0a0e1d56f0e948040d8b57c0416879183cac1937fa2b99e5c00a2a284099fba1dfb93276007094b552fe08e9c17ac
data/README.md CHANGED
@@ -1,179 +1,263 @@
1
- # Settings Gem
2
-
3
- This is improved from rails-settings, added caching for all settings.
4
- Settings is a plugin that makes managing a table of global key, value pairs easy.
5
- Think of it like a global Hash stored in you database, that uses simple ActiveRecord
6
- like methods for manipulation. Keep track of any global setting that you dont want
7
- to hard code into your rails app. You can store any kind of object. Strings, numbers,
8
- arrays, or any object. Ported to Rails 3!
9
-
10
- ## Status
11
-
12
- - [![Gem Version](https://badge.fury.io/rb/rails-settings-cached.png)](https://rubygems.org/gems/rails-settings-cached)
13
- - [![CI Status](https://api.travis-ci.org/huacnlee/rails-settings-cached.png)](http://travis-ci.org/huacnlee/rails-settings-cached)
14
-
15
- ## Setup
16
-
17
- Edit your Gemfile:
18
-
19
- ```ruby
20
- # Rails 4.1.x
21
- gem "rails-settings-cached", "0.4.1"
22
- # Rails 4+
23
- gem "rails-settings-cached", "0.3.1"
24
- # Rails 3.x
25
- gem "rails-settings-cached", "0.2.4"
26
- ```
27
-
28
- Generate your settings:
29
-
30
- ```bash
31
- $ rails g settings <settings_name>
32
- ```
33
-
34
- Note: If you migrating from gem `rails-settings` then make sure you have it in your model
35
-
36
- ```ruby
37
- class Settings < RailsSettings::CachedSettings
38
- ...
39
- end
40
- ```
41
-
42
- Now just put that migration in the database with:
43
-
44
- ```bash
45
- rake db:migrate
46
- ```
47
-
48
- ## Usage
49
-
50
- The syntax is easy. First, lets create some settings to keep track of:
51
-
52
- ```ruby
53
- Setting.admin_password = 'supersecret'
54
- Setting.date_format = '%m %d, %Y'
55
- Setting.cocktails = ['Martini', 'Screwdriver', 'White Russian']
56
- Setting.foo = 123
57
- Setting.credentials = { :username => 'tom', :password => 'secret' }
58
- ```
59
-
60
- Now lets read them back:
61
-
62
- ```ruby
63
- Setting.foo # returns 123
64
- ```
65
-
66
- Changing an existing setting is the same as creating a new setting:
67
-
68
- ```ruby
69
- Setting.foo = 'super duper bar'
70
- ```
71
-
72
- For changing an existing setting which is a Hash, you can merge new values with existing ones:
73
-
74
- ```ruby
75
- Setting.merge!(:credentials, :password => 'topsecret')
76
- Setting.credentials # returns { :username => 'tom', :password => 'topsecret' }
77
- ```
78
-
79
- Decide you dont want to track a particular setting anymore?
80
-
81
- ```ruby
82
- Setting.destroy :foo
83
- Setting.foo # returns nil
84
- ```
85
-
86
- Want a list of all the settings?
87
-
88
- ```ruby
89
- Setting.get_all
90
- # returns {'admin_password' => 'super_secret', 'date_format' => '%m %d, %Y'}
91
- ```
92
-
93
- You need name spaces and want a list of settings for a give name space? Just choose your prefered named space delimiter and use Setting.get_all like this:
94
-
95
- ```ruby
96
- Setting['preferences.color'] = :blue
97
- Setting['preferences.size'] = :large
98
- Setting['license.key'] = 'ABC-DEF'
99
- Setting.get_all('preferences.')
100
- # returns { 'preferences.color' => :blue, 'preferences.size' => :large }
101
- ```
102
-
103
- Set defaults for certain settings of your app. This will cause the defined settings to return with the
104
- Specified value even if they are **not in the database**. Make a new file in `config/initializers/default_settings.rb`
105
- with the following:
106
-
107
- ```ruby
108
- Setting.defaults[:some_setting] = 'footastic'
109
- Setting.where(:var => "some_setting").count
110
- => 0
111
- Setting.some_setting
112
- => "footastic"
113
- ```
114
-
115
- Init defualt value in database, this has indifferent with `Setting.defaults[:some_setting]`, this will **save the value into database**:
116
-
117
- ```ruby
118
- Setting.save_default(:some_key, "123")
119
- Setting.where(:var => "some_key").count
120
- => 1
121
- Setting.some_key
122
- => "123"
123
- ```
124
-
125
- Settings may be bound to any existing ActiveRecord object. Define this association like this:
126
- Notice! is not do caching in this version.
127
-
128
- ```ruby
129
- class User < ActiveRecord::Base
130
- include RailsSettings::Extend
131
- end
132
- ```
133
-
134
- Then you can set/get a setting for a given user instance just by doing this:
135
-
136
- ```ruby
137
- user = User.find(123)
138
- user.settings.color = :red
139
- user.settings.color # returns :red
140
- user.settings.get_all # { "color" => :red }
141
- ```
142
-
143
- I you want to find users having or not having some settings, there are named scopes for this:
144
-
145
- ```ruby
146
- User.with_settings
147
- # => returns a scope of users having any setting
148
-
149
- User.with_settings_for('color')
150
- # => returns a scope of users having a 'color' setting
151
-
152
- User.without_settings
153
- # returns a scope of users having no setting at all (means user.settings.get_all == {})
154
-
155
- User.without_settings('color')
156
- # returns a scope of users having no 'color' setting (means user.settings.color == nil)
157
- ```
158
-
159
- -----
160
-
161
- ## How to create a list, form to manage Settings?
162
-
163
- If you want create an admin interface to editing the Settings, you can try methods in follow:
164
-
165
- ```ruby
166
- class SettingsController < ApplicationController
167
- def index
168
- # to get all items for render list
169
- @settings = Setting.unscoped
170
- end
171
-
172
- def edit
173
- @setting = Setting.unscoped.find(params[:id])
174
- end
175
- end
176
- ```
177
-
178
-
179
- That's all there is to it! Enjoy!
1
+ # Rails Settings Cached
2
+
3
+ This is improved from [rails-settings](https://github.com/ledermann/rails-settings),
4
+ added caching for all settings. Settings is a plugin that makes managing a table of
5
+ global key, value pairs easy. Think of it like a global Hash stored in your database,
6
+ that uses simple ActiveRecord like methods for manipulation. Keep track of any global
7
+ setting that you dont want to hard code into your rails app. You can store any kind
8
+ of object. Strings, numbers, arrays, or any object.
9
+
10
+ ## Status
11
+
12
+ [![Gem Version](https://badge.fury.io/rb/rails-settings-cached.svg)](https://rubygems.org/gems/rails-settings-cached) [![CI Status](https://api.travis-ci.org/huacnlee/rails-settings-cached.svg)](http://travis-ci.org/huacnlee/rails-settings-cached) [![Code Climate](https://codeclimate.com/github/huacnlee/rails-settings-cached/badges/gpa.svg)](https://codeclimate.com/github/huacnlee/rails-settings-cached) [![codecov.io](https://codecov.io/github/huacnlee/rails-settings-cached/coverage.svg?branch=master)](https://codecov.io/github/huacnlee/rails-settings-cached?branch=master)
13
+
14
+ ## Setup
15
+
16
+ Edit your Gemfile:
17
+
18
+ ```ruby
19
+ gem "rails-settings-cached"
20
+ ```
21
+
22
+ Generate your settings:
23
+
24
+ ```bash
25
+ $ rails g settings:install
26
+ ```
27
+
28
+ If you want custom model name:
29
+
30
+ ```bash
31
+ $ rails g settings:install SiteConfig
32
+ ```
33
+
34
+ Now just put that migration in the database with:
35
+
36
+ ```bash
37
+ rake db:migrate
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ The syntax is easy. First, lets create some settings to keep track of:
43
+
44
+ ```ruby
45
+ Setting.admin_password = 'supersecret'
46
+ Setting.date_format = '%m %d, %Y'
47
+ Setting.cocktails = ['Martini', 'Screwdriver', 'White Russian']
48
+ Setting.foo = 123
49
+ Setting.credentials = { :username => 'tom', :password => 'secret' }
50
+ ```
51
+
52
+ Now lets read them back:
53
+
54
+ ```ruby
55
+ Setting.foo # returns 123
56
+ ```
57
+
58
+ Changing an existing setting is the same as creating a new setting:
59
+
60
+ ```ruby
61
+ Setting.foo = 'super duper bar'
62
+ ```
63
+
64
+ Decide you dont want to track a particular setting anymore?
65
+
66
+ ```ruby
67
+ Setting.destroy :foo
68
+ Setting.foo # returns nil
69
+ ```
70
+
71
+ Want a list of all the settings?
72
+ ```ruby
73
+ Setting.get_all
74
+ ```
75
+
76
+ You need name spaces and want a list of settings for a give name space? Just choose your prefered named space delimiter and use `Setting.get_all` (`Settings.all` for # Rails 3.x and 4.0.x) like this:
77
+
78
+ ```ruby
79
+ Setting['preferences.color'] = :blue
80
+ Setting['preferences.size'] = :large
81
+ Setting['license.key'] = 'ABC-DEF'
82
+ # Rails 4.1.x
83
+ Setting.get_all('preferences.')
84
+ # Rails 3.x and 4.0.x
85
+ Setting.all('preferences.')
86
+ # returns { 'preferences.color' => :blue, 'preferences.size' => :large }
87
+ ```
88
+
89
+ ## Extend a model
90
+
91
+ Settings may be bound to any existing ActiveRecord object. Define this association like this:
92
+ Notice! is not do caching in this version.
93
+
94
+ ```ruby
95
+ class User < ActiveRecord::Base
96
+ include RailsSettings::Extend
97
+ end
98
+ ```
99
+
100
+ Then you can set/get a setting for a given user instance just by doing this:
101
+
102
+ ```ruby
103
+ user = User.find(123)
104
+ user.settings.color = :red
105
+ user.settings.color # returns :red
106
+ user.settings.get_all
107
+ # { "color" => :red }
108
+ ```
109
+
110
+ If you want to find users having or not having some settings, there are named scopes for this:
111
+
112
+ ```ruby
113
+ User.with_settings
114
+ # => returns a scope of users having any setting
115
+
116
+ User.with_settings_for('color')
117
+ # => returns a scope of users having a 'color' setting
118
+
119
+ User.without_settings
120
+ # returns a scope of users having no setting at all (means user.settings.get_all == {})
121
+
122
+ User.without_settings('color')
123
+ # returns a scope of users having no 'color' setting (means user.settings.color == nil)
124
+ ```
125
+
126
+ ## Default settings
127
+
128
+ Sometimes you may want define default settings.
129
+
130
+ RailsSettings has generate a config YAML file in:
131
+
132
+ ```yml
133
+ # config/app.yml
134
+ defaults: &defaults
135
+ github_token: "123456"
136
+ twitter_token: "<%= ENV["TWITTER_TOKEN"] %>"
137
+ foo:
138
+ bar: "Foo bar"
139
+
140
+ development:
141
+ <<: *defaults
142
+
143
+ test:
144
+ <<: *defaults
145
+
146
+ production:
147
+ <<: *defaults
148
+ ```
149
+
150
+ And you can use by `Setting` model:
151
+
152
+ ```
153
+ Setting.github_token
154
+ => "123456"
155
+ Setting.github_token = "654321"
156
+ # Save into database.
157
+ Setting.github_token
158
+ # Read from databae / caching.
159
+ => "654321"
160
+ Setting['foo.bar']
161
+ => 'Foo bar'
162
+ ```
163
+
164
+ NOTE: YAML setting it also under the cache scope, when you restart Rails application, cache will expire,
165
+ so when you want change default config, you need restart Rails application server.
166
+
167
+ ### Caching flow:
168
+
169
+ ```
170
+ Setting.foo -> Check Cache -> Exist - Write Cache -> Return
171
+ |
172
+ Check DB -> Exist -> Write Cache -> Return
173
+ |
174
+ Check Default -> Exist -> Write Cache -> Return
175
+ |
176
+ Return nil
177
+ ```
178
+
179
+ ## Change cache key
180
+
181
+ ```ruby
182
+ class Setting < RailsSettings::Base
183
+ cache_prefix { 'you-prefix' }
184
+ ...
185
+ end
186
+ ```
187
+
188
+ -----
189
+
190
+ ## How to create a list, form to manage Settings?
191
+
192
+ If you want create an admin interface to editing the Settings, you can try methods in follow:
193
+
194
+ config/routes.rb
195
+
196
+ ```rb
197
+ namespace :admin do
198
+ resources :settings
199
+ end
200
+ ```
201
+
202
+
203
+ app/controllers/admin/settings_controller.rb
204
+
205
+ ```rb
206
+ module Admin
207
+ class SettingsController < ApplicationController
208
+ before_action :get_setting, only: [:edit, :update]
209
+
210
+ def index
211
+ @settings = Setting.get_all
212
+ end
213
+
214
+ def edit
215
+ end
216
+
217
+ def update
218
+ if @setting.value != params[:setting][:value]
219
+ @setting.value = YAML.load(params[:setting][:value])
220
+ @setting.save
221
+ redirect_to admin_settings_path, notice: 'Setting has updated.'
222
+ else
223
+ redirect_to admin_settings_path
224
+ end
225
+ end
226
+
227
+ def get_setting
228
+ @setting = Setting.find_by(var: params[:id]) || Setting.new(var: params[:id])
229
+ @setting[:value] = Setting[params[:id]]
230
+ end
231
+ end
232
+ end
233
+ ```
234
+
235
+ app/views/admin/settings/index.html.erb
236
+
237
+ ```erb
238
+ <table>
239
+ <tr>
240
+ <th>Key</th>
241
+ <th></th>
242
+ </tr>
243
+ <% @settings.each_key do |key| %>
244
+ <tr>
245
+ <td><%= key %></td>
246
+ <td><%= link_to 'edit', edit_admin_setting_path(key) %></td>
247
+ </tr>
248
+ <% end %>
249
+ </table>
250
+ ```
251
+
252
+ app/views/admin/settings/edit.html.erb
253
+
254
+ ```erb
255
+ <%= form_for(@setting, url: admin_setting_path(@setting.var), method: 'patch') do |f| %>
256
+ <label><%= @setting.var %></label>
257
+ <%= f.textarea :value, rows: 10 %>
258
+ <%= f.submit %>
259
+ <% end %>
260
+ ```
261
+
262
+ Also you may use [rails-settings-ui](https://github.com/accessd/rails-settings-ui) gem
263
+ for building ready to using interface with validations.
@@ -0,0 +1,34 @@
1
+ require 'rails/generators'
2
+ require 'rails/generators/migration'
3
+
4
+ module Settings
5
+ class InstallGenerator < Rails::Generators::NamedBase
6
+ desc "Generate RailsSettings files."
7
+ include Rails::Generators::Migration
8
+
9
+ argument :name, type: :string, default: 'setting'
10
+
11
+ source_root File.expand_path('../templates', __FILE__)
12
+
13
+ @@migrations = false
14
+
15
+ def self.next_migration_number(dirname) #:nodoc:
16
+ if ActiveRecord::Base.timestamped_migrations
17
+ if @@migrations
18
+ (current_migration_number(dirname) + 1)
19
+ else
20
+ @@migrations = true
21
+ Time.now.utc.strftime('%Y%m%d%H%M%S')
22
+ end
23
+ else
24
+ format '%.3d', current_migration_number(dirname) + 1
25
+ end
26
+ end
27
+
28
+ def install_setting
29
+ template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb")
30
+ template 'app.yml', File.join('config', "app.yml")
31
+ migration_template 'migration.rb', 'db/migrate/create_settings.rb'
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,13 @@
1
+ # config/app.yml for rails-settings-cached
2
+ defaults: &defaults
3
+ foo: "Foo"
4
+ bar: 123
5
+
6
+ development:
7
+ <<: *defaults
8
+
9
+ test:
10
+ <<: *defaults
11
+
12
+ production:
13
+ <<: *defaults
@@ -1,14 +1,14 @@
1
1
  class CreateSettings < ActiveRecord::Migration
2
2
  def self.up
3
3
  create_table :settings do |t|
4
- t.string :var, :null => false
5
- t.text :value, :null => true
6
- t.integer :thing_id, :null => true
7
- t.string :thing_type, :limit => 30, :null => true
4
+ t.string :var, null: false
5
+ t.text :value, null: true
6
+ t.integer :thing_id, null: true
7
+ t.string :thing_type, null: true, limit: 30
8
8
  t.timestamps
9
9
  end
10
-
11
- add_index :settings, [ :thing_type, :thing_id, :var ], :unique => true
10
+
11
+ add_index :settings, %i(thing_type thing_id var), unique: true
12
12
  end
13
13
 
14
14
  def self.down
@@ -1,2 +1,5 @@
1
+ # RailsSettings Model
1
2
  class <%= class_name %> < RailsSettings::CachedSettings
3
+ source Rails.root.join("config/app.yml")
4
+ namespace Rails.env
2
5
  end
@@ -0,0 +1,56 @@
1
+ module RailsSettings
2
+ class Base < Settings
3
+ def rewrite_cache
4
+ Rails.cache.write(cache_key, value)
5
+ end
6
+
7
+ def expire_cache
8
+ Rails.cache.delete(cache_key)
9
+ end
10
+
11
+ def cache_key
12
+ self.class.cache_key(var, thing)
13
+ end
14
+
15
+ class << self
16
+ def cache_prefix_by_startup
17
+ @cache_prefix_by_startup ||= Time.now.to_f.to_s
18
+ end
19
+
20
+ def cache_prefix(&block)
21
+ @cache_prefix = block
22
+ end
23
+
24
+ def cache_key(var_name, scope_object)
25
+ scope = ["rails_settings_cached", cache_prefix_by_startup]
26
+ scope << @cache_prefix.call if @cache_prefix
27
+ scope << "#{scope_object.class.name}-#{scope_object.id}" if scope_object
28
+ scope << var_name.to_s
29
+ scope.join('/')
30
+ end
31
+
32
+ def [](key)
33
+ val = Rails.cache.fetch(cache_key(key, @object)) do
34
+ super(key)
35
+ end
36
+ val
37
+ end
38
+
39
+ # set a setting value by [] notation
40
+ def []=(var_name, value)
41
+ super
42
+
43
+ Rails.cache.write(cache_key(var_name, @object),value)
44
+
45
+ value
46
+ end
47
+
48
+ def save_default(key, value)
49
+ Kernel.warn 'DEPRECATION WARNING: RailsSettings save_default is deprecated and it will removed in 0.7.0. ' <<
50
+ 'Please use YAML file for default setting.'
51
+ return false unless self[key].nil?
52
+ self[key] = value
53
+ end
54
+ end
55
+ end
56
+ end
@@ -1,25 +1,9 @@
1
1
  module RailsSettings
2
- class CachedSettings < Settings
3
- after_update :rewrite_cache
4
- after_create :rewrite_cache
5
- def rewrite_cache
6
- Rails.cache.write("settings:#{self.var}", self.value)
7
- end
8
-
9
- after_destroy { |record| Rails.cache.delete("settings:#{record.var}") }
10
-
11
- def self.[](var_name)
12
- cache_key = "settings:#{var_name}"
13
- obj = Rails.cache.fetch(cache_key) {
14
- super(var_name)
15
- }
16
- obj == nil ? @@defaults[var_name.to_s] : obj
17
- end
18
-
19
- def self.save_default(key,value)
20
- if self.send(key) == nil
21
- self.send("#{key}=",value)
22
- end
2
+ class CachedSettings < Base
3
+ def self.inherited(subclass)
4
+ Kernel.warn 'DEPRECATION WARNING: RailsSettings::CachedSettings is deprecated and it will removed in 0.7.0. ' <<
5
+ 'Please use RailsSettings::Base instead.'
6
+ super(subclass)
23
7
  end
24
8
  end
25
- end
9
+ end
@@ -0,0 +1,43 @@
1
+ module RailsSettings
2
+ class Default < ::Hash
3
+ class MissingKey < StandardError; end
4
+
5
+ class << self
6
+ def enabled?
7
+ source_path && File.exists?(source_path)
8
+ end
9
+
10
+ def source(value = nil)
11
+ @source ||= value
12
+ end
13
+
14
+ def source_path
15
+ @source || Rails.root.join('config/app.yml')
16
+ end
17
+
18
+ def [](key)
19
+ # foo.bar.dar Nested fetch value
20
+ keys = key.to_s.split('.')
21
+ val = instance
22
+ keys.each do |k|
23
+ val = val.fetch(k.to_s, nil)
24
+ break if val.nil?
25
+ end
26
+ val
27
+ end
28
+
29
+ def instance
30
+ return @instance if defined? @instance
31
+ @instance = new
32
+ @instance
33
+ end
34
+ end
35
+
36
+ def initialize
37
+ content = open(self.class.source_path).read
38
+ hash = content.empty? ? {} : YAML.load(ERB.new(content).result).to_hash
39
+ hash = hash[Rails.env] || {}
40
+ self.replace hash
41
+ end
42
+ end
43
+ end
@@ -1,37 +1,34 @@
1
1
  module RailsSettings
2
2
  module Extend
3
3
  extend ActiveSupport::Concern
4
-
5
- included do
6
- scope :with_settings, -> {
7
- joins("JOIN settings ON (settings.thing_id = #{self.table_name}.#{self.primary_key} AND
8
- settings.thing_type = '#{self.base_class.name}')")
9
- .select("DISTINCT #{self.table_name}.*")
10
- }
11
-
12
4
 
13
- scope :with_settings_for, ->(var) {
14
- joins("JOIN settings ON (settings.thing_id = #{self.table_name}.#{self.primary_key} AND
15
- settings.thing_type = '#{self.base_class.name}') AND settings.var = '#{var}'")
5
+ included do
6
+ scope :with_settings, lambda {
7
+ joins("JOIN settings ON (settings.thing_id = #{table_name}.#{primary_key} AND
8
+ settings.thing_type = '#{base_class.name}')")
9
+ .select("DISTINCT #{table_name}.*")
16
10
  }
17
-
18
- scope :without_settings, -> {
19
- joins("LEFT JOIN settings ON (settings.thing_id = #{self.table_name}.#{self.primary_key} AND settings.thing_type = '#{self.base_class.name}')")
20
- .where("settings.id IS NULL")
21
- }
22
-
23
- scope :without_settings_for, ->(var) {
11
+
12
+ scope :with_settings_for, lambda { |var|
13
+ joins("JOIN settings ON (settings.thing_id = #{table_name}.#{primary_key} AND
14
+ settings.thing_type = '#{base_class.name}') AND settings.var = '#{var}'")
15
+ }
16
+
17
+ scope :without_settings, lambda {
18
+ joins("LEFT JOIN settings ON (settings.thing_id = #{table_name}.#{primary_key} AND
19
+ settings.thing_type = '#{base_class.name}')")
20
+ .where('settings.id IS NULL')
21
+ }
22
+
23
+ scope :without_settings_for, lambda { |var|
24
24
  where('settings.id IS NULL')
25
- .joins("LEFT JOIN settings ON (settings.thing_id = #{self.table_name}.#{self.primary_key} AND
26
- settings.thing_type = '#{self.base_class.name}') AND settings.var = '#{var}'")
25
+ .joins("LEFT JOIN settings ON (settings.thing_id = #{table_name}.#{primary_key} AND
26
+ settings.thing_type = '#{base_class.name}') AND settings.var = '#{var}'")
27
27
  }
28
-
29
28
  end
30
-
29
+
31
30
  def settings
32
31
  ScopedSettings.for_thing(self)
33
32
  end
34
33
  end
35
34
  end
36
-
37
-
@@ -1,13 +1,12 @@
1
1
  module RailsSettings
2
- class ScopedSettings < Settings
2
+ class ScopedSettings < Base
3
3
  def self.for_thing(object)
4
4
  @object = object
5
5
  self
6
6
  end
7
-
7
+
8
8
  def self.thing_scoped
9
- unscoped.where(:thing_type => @object.class.base_class.to_s, :thing_id => @object.id)
9
+ unscoped.where(thing_type: @object.class.base_class.to_s, thing_id: @object.id)
10
10
  end
11
-
12
11
  end
13
- end
12
+ end
@@ -1,118 +1,119 @@
1
1
  module RailsSettings
2
2
  class Settings < ActiveRecord::Base
3
-
4
3
  self.table_name = table_name_prefix + 'settings'
5
4
 
6
5
  class SettingNotFound < RuntimeError; end
7
6
 
8
- cattr_accessor :defaults
9
- @@defaults = {}.with_indifferent_access
7
+ belongs_to :thing, polymorphic: true
10
8
 
11
- # Support old plugin
12
- if defined?(SettingsDefaults::DEFAULTS)
13
- @@defaults = SettingsDefaults::DEFAULTS.with_indifferent_access
9
+ # get the value field, YAML decoded
10
+ def value
11
+ YAML.load(self[:value]) if self[:value].present?
14
12
  end
15
13
 
16
- #get or set a variable with the variable as the called method
17
- def self.method_missing(method, *args)
18
- method_name = method.to_s
19
- super(method, *args)
20
- rescue NoMethodError
21
- #set a value for a variable
22
- if method_name =~ /=$/
23
- var_name = method_name.gsub('=', '')
24
- value = args.first
25
- self[var_name] = value
26
- #retrieve a value
27
- else
28
- self[method_name]
29
- end
14
+ # set the value field, YAML encoded
15
+ def value=(new_value)
16
+ self[:value] = new_value.to_yaml
30
17
  end
31
18
 
32
- #destroy the specified settings record
33
- def self.destroy(var_name)
34
- var_name = var_name.to_s
35
- obj = object(var_name)
36
- unless obj.nil?
19
+ class << self
20
+ # get or set a variable with the variable as the called method
21
+ def method_missing(method, *args)
22
+ method_name = method.to_s
23
+ super(method, *args)
24
+ rescue NoMethodError
25
+ # set a value for a variable
26
+ if method_name[-1] == '='
27
+ var_name = method_name.sub('=', '')
28
+ value = args.first
29
+ self[var_name] = value
30
+ else
31
+ # retrieve a value
32
+ self[method_name]
33
+ end
34
+ end
35
+
36
+ # destroy the specified settings record
37
+ def destroy(var_name)
38
+ var_name = var_name.to_s
39
+ obj = object(var_name)
40
+ raise SettingNotFound, "Setting variable \"#{var_name}\" not found" if obj.nil?
41
+
37
42
  obj.destroy
38
43
  true
39
- else
40
- raise SettingNotFound, "Setting variable \"#{var_name}\" not found"
41
44
  end
42
- end
43
45
 
44
- #retrieve all settings as a hash (optionally starting with a given namespace)
45
- def self.get_all(starting_with = nil)
46
- vars = thing_scoped.select("var,value")
47
- if starting_with
48
- vars = vars.where("var LIKE '#{starting_with}%'")
49
- end
46
+ # retrieve all settings as a hash (optionally starting with a given namespace)
47
+ def get_all(starting_with = nil)
48
+ vars = thing_scoped.select('var, value')
49
+ vars = vars.where("var LIKE '#{starting_with}%'") if starting_with
50
50
 
51
- result = {}
52
- vars.each do |record|
53
- result[record.var] = record.value
54
- end
55
- result.with_indifferent_access
56
- end
57
-
58
- def self.where(sql = nil)
59
- if sql
60
- vars = thing_scoped.where(sql)
51
+ result = {}
52
+ vars.each do |record|
53
+ result[record.var] = record.value
54
+ end
55
+
56
+ defaults = {}
57
+ if Default.enabled?
58
+ defaults = starting_with.nil? ? Default.instance : Default.instance.fetch(starting_with, {})
59
+ end
60
+
61
+ result.merge! defaults
62
+
63
+ result.with_indifferent_access
61
64
  end
62
- vars
63
- end
64
-
65
- #get a setting value by [] notation
66
- def self.[](var_name)
67
- if var = object(var_name)
68
- var.value
69
- elsif @@defaults[var_name.to_s]
70
- @@defaults[var_name.to_s]
71
- else
72
- nil
65
+
66
+ def where(sql = nil)
67
+ vars = thing_scoped.where(sql) if sql
68
+ vars
73
69
  end
74
- end
75
70
 
76
- #set a setting value by [] notation
77
- def self.[]=(var_name, value)
78
- var_name = var_name.to_s
71
+ # get a setting value by [] notation
72
+ def [](var_name)
73
+ if var = object(var_name)
74
+ val = var.value
75
+ elsif Default.enabled?
76
+ val = Default[var_name]
77
+ else
78
+ val = nil
79
+ end
80
+ val
81
+ end
79
82
 
80
- record = object(var_name) || thing_scoped.new(:var => var_name)
81
- record.value = value
82
- record.save!
83
+ # set a setting value by [] notation
84
+ def []=(var_name, value)
85
+ var_name = var_name.to_s
83
86
 
84
- value
85
- end
87
+ record = object(var_name) || thing_scoped.new(var: var_name)
88
+ record.value = value
89
+ record.save!
86
90
 
87
- def self.merge!(var_name, hash_value)
88
- raise ArgumentError unless hash_value.is_a?(Hash)
91
+ value
92
+ end
89
93
 
90
- old_value = self[var_name] || {}
91
- raise TypeError, "Existing value is not a hash, can't merge!" unless old_value.is_a?(Hash)
94
+ def merge!(var_name, hash_value)
95
+ raise ArgumentError unless hash_value.is_a?(Hash)
92
96
 
93
- new_value = old_value.merge(hash_value)
94
- self[var_name] = new_value if new_value != old_value
97
+ old_value = self[var_name] || {}
98
+ raise TypeError, "Existing value is not a hash, can't merge!" unless old_value.is_a?(Hash)
95
99
 
96
- new_value
97
- end
100
+ new_value = old_value.merge(hash_value)
101
+ self[var_name] = new_value if new_value != old_value
98
102
 
99
- def self.object(var_name)
100
- thing_scoped.where(:var => var_name.to_s).first
101
- end
103
+ new_value
104
+ end
102
105
 
103
- #get the value field, YAML decoded
104
- def value
105
- YAML::load(self[:value])
106
- end
106
+ def object(var_name)
107
+ table_exists? && thing_scoped.where(var: var_name.to_s).first
108
+ end
107
109
 
108
- #set the value field, YAML encoded
109
- def value=(new_value)
110
- self[:value] = new_value.to_yaml
111
- end
110
+ def thing_scoped
111
+ unscoped.where('thing_type is NULL and thing_id is NULL')
112
+ end
112
113
 
113
- def self.thing_scoped
114
- unscoped.where("thing_type is NULL and thing_id is NULL")
114
+ def source(filename)
115
+ Default.source(filename)
116
+ end
115
117
  end
116
-
117
118
  end
118
119
  end
@@ -0,0 +1,7 @@
1
+ module RailsSettings
2
+ class << self
3
+ def version
4
+ "0.6.1"
5
+ end
6
+ end
7
+ end
@@ -1,4 +1,16 @@
1
- require "rails-settings/settings"
2
- require "rails-settings/scoped_settings"
3
- require "rails-settings/cached_settings"
4
- require "rails-settings/extend"
1
+ require_relative 'rails-settings/settings'
2
+ require_relative 'rails-settings/base'
3
+ require_relative 'rails-settings/cached_settings'
4
+ require_relative 'rails-settings/scoped_settings'
5
+ require_relative 'rails-settings/default'
6
+ require_relative 'rails-settings/extend'
7
+ require_relative 'rails-settings/version'
8
+
9
+ module RailsSettings
10
+ class Railtie < Rails::Railtie
11
+ initializer "rails_settings.active_record.initialization" do
12
+ RailsSettings::Base.after_commit :rewrite_cache, on: %i(create update)
13
+ RailsSettings::Base.after_commit :expire_cache, on: %i(destroy)
14
+ end
15
+ end
16
+ end
metadata CHANGED
@@ -1,17 +1,17 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails-settings-cached
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.1
4
+ version: 0.6.1
5
5
  platform: ruby
6
6
  authors:
7
+ - Jason Lee
7
8
  - Squeegy
8
9
  - Georg Ledermann
9
10
  - 100hz
10
- - Jason Lee
11
11
  autorequire:
12
12
  bindir: bin
13
13
  cert_chain: []
14
- date: 2014-05-12 00:00:00.000000000 Z
14
+ date: 2016-04-20 00:00:00.000000000 Z
15
15
  dependencies:
16
16
  - !ruby/object:Gem::Dependency
17
17
  name: rails
@@ -19,29 +19,38 @@ dependencies:
19
19
  requirements:
20
20
  - - ">="
21
21
  - !ruby/object:Gem::Version
22
- version: 4.0.0
22
+ version: 4.2.0
23
23
  type: :runtime
24
24
  prerelease: false
25
25
  version_requirements: !ruby/object:Gem::Requirement
26
26
  requirements:
27
27
  - - ">="
28
28
  - !ruby/object:Gem::Version
29
- version: 4.0.0
30
- description:
29
+ version: 4.2.0
30
+ description: "\n This is improved from rails-settings, added caching.\n Settings
31
+ plugin for Rails that makes managing a table of global key,\n value pairs easy.
32
+ Think of it like a global Hash stored in you database,\n that uses simple ActiveRecord
33
+ like methods for manipulation.\n\n Keep track of any global setting that you dont
34
+ want to hard code into your rails app.\n You can store any kind of object. Strings,
35
+ numbers, arrays, or any object.\n "
31
36
  email: huacnlee@gmail.com
32
37
  executables: []
33
38
  extensions: []
34
39
  extra_rdoc_files: []
35
40
  files:
36
41
  - README.md
37
- - lib/generators/settings/settings_generator.rb
42
+ - lib/generators/settings/install_generator.rb
43
+ - lib/generators/settings/templates/app.yml
38
44
  - lib/generators/settings/templates/migration.rb
39
45
  - lib/generators/settings/templates/model.rb
40
46
  - lib/rails-settings-cached.rb
47
+ - lib/rails-settings/base.rb
41
48
  - lib/rails-settings/cached_settings.rb
49
+ - lib/rails-settings/default.rb
42
50
  - lib/rails-settings/extend.rb
43
51
  - lib/rails-settings/scoped_settings.rb
44
52
  - lib/rails-settings/settings.rb
53
+ - lib/rails-settings/version.rb
45
54
  homepage: https://github.com/huacnlee/rails-settings-cached
46
55
  licenses: []
47
56
  metadata: {}
@@ -53,7 +62,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
53
62
  requirements:
54
63
  - - ">="
55
64
  - !ruby/object:Gem::Version
56
- version: '0'
65
+ version: '2.1'
57
66
  required_rubygems_version: !ruby/object:Gem::Requirement
58
67
  requirements:
59
68
  - - ">="
@@ -61,13 +70,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
61
70
  version: '0'
62
71
  requirements: []
63
72
  rubyforge_project:
64
- rubygems_version: 2.2.2
73
+ rubygems_version: 2.6.3
65
74
  signing_key:
66
75
  specification_version: 4
67
- summary: This is imporved from rails-settings, added caching. Settings is a plugin
68
- that makes managing a table of global key, value pairs easy. Think of it like a
69
- global Hash stored in you database, that uses simple ActiveRecord like methods for
70
- manipulation. Keep track of any global setting that you dont want to hard code
71
- into your rails app. You can store any kind of object. Strings, numbers, arrays,
72
- or any object. Ported to Rails 3!
76
+ summary: Settings plugin for Rails that makes managing a table of global keys.
73
77
  test_files: []
@@ -1,30 +0,0 @@
1
- require 'rails/generators/migration'
2
-
3
- class SettingsGenerator < Rails::Generators::NamedBase
4
- include Rails::Generators::Migration
5
-
6
- argument :name, :type => :string, :default => "my_settings"
7
-
8
- source_root File.expand_path('../templates', __FILE__)
9
-
10
- @@migrations = false
11
-
12
- def self.next_migration_number(dirname) #:nodoc:
13
- if ActiveRecord::Base.timestamped_migrations
14
- if @@migrations
15
- (current_migration_number(dirname) + 1)
16
- else
17
- @@migrations = true
18
- Time.now.utc.strftime("%Y%m%d%H%M%S")
19
- end
20
- else
21
- "%.3d" % (current_migration_number(dirname) + 1)
22
- end
23
- end
24
-
25
- def settings
26
- #generate(:model, name, "--skip-migration")
27
- template "model.rb", File.join("app/models",class_path,"#{file_name}.rb"), :force => true
28
- migration_template "migration.rb", "db/migrate/create_settings.rb"
29
- end
30
- end