has_config 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0ff4a936f1e2bb34db9f906368df5cc8e1933f03
4
+ data.tar.gz: f29d5a2372cc3ca6abecf6d4d0fc543467f94ca2
5
+ SHA512:
6
+ metadata.gz: 9154daeeedbc0ca628ab5e3a2ee87a6685eef73a492f35ebdefec323f13d69cfff7524c2845d203da3a77826ae3e7974c4be90765f93d031edd02afa9a994783
7
+ data.tar.gz: 57b678e8f2e67a71139e884c236b9c0027189c6fe1fa83dc9f9abc4bca8bd23419e492e4fda12a94753112fbe418d148e42955ea94692822423882c05ea5478d
@@ -0,0 +1,10 @@
1
+ .DS_STORE
2
+ /.bundle/
3
+ /.yardoc
4
+ /Gemfile.lock
5
+ /_yardoc/
6
+ /coverage/
7
+ /doc/
8
+ /pkg/
9
+ /spec/reports/
10
+ /tmp/
@@ -0,0 +1,16 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0
4
+ - 2.1
5
+ - 2.2
6
+ gemfile:
7
+ - gemfiles/4.0.gemfile
8
+ - gemfiles/4.1.gemfile
9
+ - gemfiles/4.2.gemfile
10
+ addons:
11
+ postgresql: '9.3'
12
+ before_script:
13
+ - psql -c 'create database has_config_test;' -U postgres
14
+ script:
15
+ - bundle exec rake test
16
+ sudo: false
@@ -0,0 +1,3 @@
1
+ ## 0.1.0 (6/20/2015)
2
+
3
+ * Initial release
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http:contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in has_config.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Tony Drake
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,135 @@
1
+ # HasConfig
2
+
3
+ [![Build Status](https://travis-ci.org/t27duck/has_config.svg?branch=master)](https://travis-ci.org/t27duck/has_config)
4
+
5
+ Tested against Ruby 2.0 - 2.2 with ActiveRecord 4.0 - 4.2
6
+
7
+ When working with models in a large Rails project, you sometimes end up with "god objects" which start to be loaded down with several booleans, integers, and strings from select boxes that act as configuration options. As time goes on, you add more and more columns. As your database and user-base grows, adding even a single column more can bring your app to a hault during a deploy due to table locking or a slew of exceptions due to [issues and gotchas like this](https://github.com/rails/rails/issues/12330).
8
+
9
+ In an attempt to cut down on cluttering your model with boolean columns, `has_config` allows you to have a single column contain all configuration switches you could ever want. Adding another configuration option to a model no longer requires a migration to add a column. You can also contiue writing code as if the model had all of those indiviual attributes.
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'has_config'
17
+ ```
18
+
19
+ And then execute:
20
+
21
+ $ bundle
22
+
23
+ Or install it yourself as:
24
+
25
+ $ gem install has_config
26
+
27
+ ## Usage
28
+
29
+ Let's say we have a model called `Client` whose job is to hold the general information configuration for a client in a multi-tenant application. First, we need to add one column to the model to hold the configuration information. By default, the gem assumes the column's name is `configuration`, but you can change that (more on that later).
30
+
31
+ ```ruby
32
+ class AddConfigurationToClients < ActiveRecord::Migration
33
+ add_column :clients, :configuration, :text
34
+ end
35
+ ```
36
+
37
+ We now want to make that column a serialized hash in our model and include the `HasConfig` module.
38
+
39
+ ```ruby
40
+ class Client < ActiveRecord::Base
41
+ serialize :configuration, Hash
42
+ include HasConfig
43
+ end
44
+ ```
45
+
46
+ If you are using PostgreSQL 9.2 or later, you can use the JSON data-type for the configuration column and not have to declare it as a serilaized attribute in the model as `ActiveRecord` will take care of that for you.
47
+
48
+ If you want to use a different column name, you may override the default by setting `self.configuration_column = 'other_column_name'` in the model.
49
+
50
+ Finally, we're going to tell our model what configuration it'll hold. We do this via the `has_config` method the module provides. For now, here's a sensory overload example. We'll go into detail in the next part.
51
+
52
+ ```ruby
53
+ class Client < ActiveRecord::Base
54
+ serialize :configuration, Hash
55
+ include HasConfig
56
+ has_config :primary_color, :string, default: 'green', group: :style
57
+ has_config :secondary_color, :string, group: :style
58
+ has_config :rate_limit, :integer, validations: { numericality: { only_integer: true } }
59
+ has_config :category, :string, validations: { inclusion: { in: CATEGORIES } }
60
+ has_config :active, :boolean, default: false
61
+ end
62
+ ```
63
+
64
+ Let's look at the `has_config` signature first before we go any further:
65
+
66
+ ```ruby
67
+ has_config(key, type, default:nil, group:nil, validations:{})
68
+ ```
69
+
70
+ At minimum, you must provide a `key` and `type`. The `key` is what you'll call this configuraiton item. The `type` can be either `:string`, `:integer`, or `:boolean`.
71
+
72
+ If a configuration item doesn't have a value, `nil` is returned by default. Or, you may provide your own default value with the `default` option.
73
+
74
+ If you have a series of configuraiton items are are related, you can organize them together with the `group` option.
75
+
76
+ To the app, each configuraiton item is like a pseudo attribute on the model. Modle attributes can have validations. Use the `validations` option to pass in a hash of options you'd normally pass into the `validates` method for a regular attribute on the model.
77
+
78
+ Ok, still with me? Back to our example...
79
+
80
+ Here, the `Client` model has five configuration items on it: `primary_color`, `secondary_color`, `rate_limit`, `category`, and `active`. So, knowing what you just learned above...
81
+
82
+ `primary_color` is a string with a default value of green and grouped in the "style" group of configuration options.
83
+
84
+ `secondary_color` is a string without a default. It too is in the "style" group.
85
+
86
+ `rate_limit` is an integer that validates its value is in fact, an integer.
87
+
88
+ `category` is a string that must be a value in the array `CATEGORIES`.
89
+
90
+ `active` is a boolean value with a default of `false`.
91
+
92
+ We can now access these configuration settings as if they were regular attributes on the model:
93
+
94
+ ```irb
95
+ client = Client.new
96
+ client.default_color
97
+ => "green"
98
+ client.secondary_color
99
+ => nil
100
+ client.active
101
+ => false
102
+ client.active?
103
+ => false
104
+ client.active = '1' # Like if this was submitted from a form
105
+ => '1'
106
+ client.active?
107
+ => true
108
+ client.rate_limit = 3
109
+ => 3
110
+ client.valid?
111
+ => false
112
+ client.errors.full_messages
113
+ => ["Category is not in the list"]
114
+ ```
115
+
116
+ Everything acts pretty much as you'd expect it too do. Configurations that fail validations make the record invalid. Passing in '1', 'true', `true`, etc casts boolean values. Passing in an empty string for an integer config casts as `nil`.
117
+
118
+ Finally, you can access all configuration values under a specific group with the `configuration_for_group` method.
119
+
120
+ ```irb
121
+ client.configuration_for_group(:style)
122
+ => {primary_color: 'green', secondary_color: nil}
123
+ ```
124
+
125
+ ## Testing
126
+
127
+ Tests run using a PostgreSQL database called `has_config_test`. You should be able to just create a database named that and run `bundle exec rake test`.
128
+
129
+ ## Contributing
130
+
131
+ 1. Fork it ( https://github.com/[my-github-username]/has_config/fork )
132
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
133
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
134
+ 4. Push to the branch (`git push origin my-new-feature`)
135
+ 5. Create a new Pull Request
@@ -0,0 +1,22 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ task default: :test
4
+
5
+ require "rake/testtask"
6
+ Rake::TestTask.new do |t|
7
+ t.libs << 'test'
8
+ #t.pattern = "test/**/*_test.rb"
9
+ t.pattern = "test/test*.rb"
10
+ end
11
+
12
+ desc "Run a console with the environment loaded"
13
+ task :console do
14
+ require 'has_config'
15
+
16
+ require 'active_record'
17
+ require 'pg'
18
+ require 'irb'
19
+ require 'irb/completion'
20
+ ARGV.clear
21
+ IRB.start
22
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "has_config"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gem "activerecord", "~> 4.0.0"
4
+
5
+ gemspec :path=>"../"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gem "activerecord", "~> 4.1.0"
4
+
5
+ gemspec :path=>"../"
@@ -0,0 +1,5 @@
1
+ source "https://rubygems.org"
2
+
3
+ gem "activerecord", "~> 4.2.0"
4
+
5
+ gemspec :path=>"../"
@@ -0,0 +1,30 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'has_config/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "has_config"
8
+ spec.version = HasConfig::VERSION
9
+ spec.authors = ["Tony Drake"]
10
+ spec.email = ["t27duck@gmail.com"]
11
+
12
+ spec.summary = %q{Quick record-specific configuration for your models}
13
+ spec.description = <<-DESC
14
+ Allows you to include and organize configuration options for each record in
15
+ a model without the need of complex joins to settings tables or constantly
16
+ adding random boolean and string columns
17
+ DESC
18
+ spec.homepage = "http://github.com/t27duck/has_config"
19
+ spec.license = "MIT"
20
+
21
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_development_dependency "bundler"
27
+ spec.add_development_dependency "rake", "~> 10.0"
28
+ spec.add_development_dependency "activerecord", ">= 4.0"
29
+ spec.add_development_dependency "pg"
30
+ end
@@ -0,0 +1,93 @@
1
+ require "has_config/version"
2
+
3
+ module HasConfig
4
+ def self.included(base)
5
+ base.extend ClassMethods
6
+ end
7
+
8
+ def configuration_for_group(group_name)
9
+ group_config = {}
10
+ (self.class.configuration_groups[group_name.to_s] || {}).each do |config_name|
11
+ group_config[config_name.to_sym] = public_send(config_name)
12
+ end
13
+ group_config
14
+ end
15
+
16
+ module ClassMethods
17
+ def has_config(key, type, default:nil, group:nil, validations:{})
18
+ raise ArgumentError, "Invalid type #{type}" unless [:string, :integer, :boolean].include?(type)
19
+
20
+ define_configuration_getter(key, default, type == :boolean)
21
+ define_configuration_setter(key, type)
22
+ set_configuration_group(key, group) if group.present?
23
+ set_configuration_validations(key, validations) if validations.present?
24
+ end
25
+
26
+ def configuration_groups
27
+ @configuration_groups ||= {}
28
+ end
29
+
30
+ def configuration_column
31
+ @configuration_column ||= 'configuration'
32
+ end
33
+
34
+ def configuration_column=(column_name)
35
+ @configuration_column = column_name.to_s
36
+ end
37
+
38
+ private ####################################################################
39
+
40
+ def define_configuration_getter(key, default, include_boolean=false)
41
+ define_method(key) do
42
+ config = (attributes[self.class.configuration_column] || {})
43
+ config[key.to_s].nil? ? default : config[key.to_s]
44
+ end
45
+
46
+ if include_boolean
47
+ define_method("#{key}?") do
48
+ config = (attributes[self.class.configuration_column] || {})
49
+ config[key.to_s].nil? ? default : config[key.to_s]
50
+ end
51
+ end
52
+ end
53
+
54
+ def define_configuration_setter(key, type)
55
+ define_method("#{key}=") do |input|
56
+ config = (attributes[self.class.configuration_column] || {})
57
+ original_value = config[key.to_s]
58
+ parsed_value = nil
59
+
60
+ if !input.nil?
61
+ parsed_value = case type
62
+ when :string
63
+ input.to_s
64
+ when :integer
65
+ input.present? ? input.to_i : nil
66
+ when :boolean
67
+ ([true,1].include?(input) || input =~ (/(true|t|yes|y|1)$/i)) ? true : false
68
+ end
69
+ end
70
+
71
+ if original_value != parsed_value
72
+ config[key.to_s] = parsed_value
73
+ write_attribute(self.class.configuration_column, config)
74
+ public_send("#{self.class.configuration_column}_will_change!")
75
+ end
76
+
77
+ input
78
+ end
79
+ end
80
+
81
+ def set_configuration_group(key, group)
82
+ @configuration_groups ||= {}
83
+ @configuration_groups[group.to_s] ||= []
84
+ @configuration_groups[group.to_s] << key.to_s
85
+ end
86
+
87
+ def set_configuration_validations(key, validation_config)
88
+ validates key, validation_config
89
+ end
90
+
91
+ end
92
+
93
+ end
@@ -0,0 +1,3 @@
1
+ module HasConfig
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: has_config
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Tony Drake
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-03-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: activerecord
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '4.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '4.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pg
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: |2
70
+ Allows you to include and organize configuration options for each record in
71
+ a model without the need of complex joins to settings tables or constantly
72
+ adding random boolean and string columns
73
+ email:
74
+ - t27duck@gmail.com
75
+ executables: []
76
+ extensions: []
77
+ extra_rdoc_files: []
78
+ files:
79
+ - ".gitignore"
80
+ - ".travis.yml"
81
+ - CHANGELOG.md
82
+ - CODE_OF_CONDUCT.md
83
+ - Gemfile
84
+ - LICENSE.txt
85
+ - README.md
86
+ - Rakefile
87
+ - bin/console
88
+ - bin/setup
89
+ - gemfiles/4.0.gemfile
90
+ - gemfiles/4.1.gemfile
91
+ - gemfiles/4.2.gemfile
92
+ - has_config.gemspec
93
+ - lib/has_config.rb
94
+ - lib/has_config/version.rb
95
+ homepage: http://github.com/t27duck/has_config
96
+ licenses:
97
+ - MIT
98
+ metadata: {}
99
+ post_install_message:
100
+ rdoc_options: []
101
+ require_paths:
102
+ - lib
103
+ required_ruby_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ requirements:
110
+ - - ">="
111
+ - !ruby/object:Gem::Version
112
+ version: '0'
113
+ requirements: []
114
+ rubyforge_project:
115
+ rubygems_version: 2.4.5.1
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: Quick record-specific configuration for your models
119
+ test_files: []