Coder Social home page Coder Social logo

paulca / configurable_engine Goto Github PK

View Code? Open in Web Editor NEW
116.0 8.0 37.0 281 KB

A Rails gem for storing app configuration data in your database, with a config file to fall back on.

License: MIT License

Ruby 71.65% HTML 16.85% JavaScript 10.89% Gherkin 0.61%

configurable_engine's Introduction

Configurable Build Status

A Rails 4 configuration engine. An update to Behavior for Rails 4.

How it works

Configurable lets you define app-wide configuration variables and values in config/configurable.yml. These can then be accessed throughout your app.

If you or your app users need to change these variables, Configurable stores new values in the database.

Installation

Configurable is available as a Ruby gem. Simply add it to your Rails 4 app's Gemfile:

gem 'configurable_engine'

Then run the configurable_engine:install generator:

$ rails generate configurable_engine:install

this will

  • add config/configurable.yml
  • create a migration for your configurable table
  • mount the UI in your routes (defaulting to admin/configurables)

Usage

There are two parts to how configurable_engine works. First of all there is a config file, config/configurable.yml. This file controls the variables that are allowed to be set in the app.

For example, if you wanted to have access to a config variable site_title, put this in configurable.yml:

site_title:
  name: Site Title
  default: My Site
  # type: String is the default

Now, within your app, you can access Configurable[:site_title] (or Configurable.site_title if you prefer).

Since Configurable is an ActiveRecord model, if you want to update the config, create a Configurable record in the database:

Configurable.create!(:name => 'site_title', :value => 'My New Site')

You can set the type attribute to boolean, decimal,integer, or list and it will treat those fields as those types. Lists are comma and/or newline delimeted arrays of strings.

Web Interface

Configurable comes with a web interface that is available to your app straight away at http://localhost:3000/admin/configurable.

If you want to add a layout, or protect the configurable controller, create app/controllers/admin/configurables_controller.rb as such:

$ bundle exec rails generate controller admin/configurables

include ConfigurableEngine::ConfigurablesController, eg.

class Admin::ConfigurablesController < ApplicationController
  # include the engine controller actions
  include ConfigurableEngine::ConfigurablesControllerMethods

  # add your own filter(s) / layout
  before_filter :protect_my_code
  layout 'admin'
end

and replace

route 'mount ConfigurableEngine::Engine, at: "/admin/configurable", as: "configurable"'

with

namespace :admin do
  resource :configurable, only: [:show, :update]
end

To ensure text areas are rendered correctly, ensure that your layout preserves whitespace. In haml, use the ~ operator

  %container
    ~ yield

If you want to control how the fields in the admin interface appear, you can add additional params in your configurable.yml file:

site_title:
  name: Name of Your Site   # sets the edit label
  default: My Site          # sets the default value
  type: string              # uses input type="text"
site_description:
  name: Describe Your Site  # sets the edit label
  default: My Site          # sets the default value
  type: text                # uses textarea
secret:
  name: A Secret Passphrase # sets the edit label
  default: passpass         # sets the default value
  type: password            # uses input type="password"

Value:
  name: A number            # sets the edit label
  default: 10               # sets the default value
  type: integer             # coerces the value to an integer

Price:
  name: A price             # sets the edit label
  default: "10.00"          # sets the default value
  type: decimal             # coerces the value to a decimal

Caching

If you want to use rails caching of Configurable updates, simply set

config.use_cache = true

in your config/application.rb (or config/production.rb)

Styling the interface

To style the web interface you are advised to use Sass. Here's an example scss file that will make the interface bootstrap-3 ready:

@import 'bootstrap';

.configurable-container {
  @extend .col-md-6;

  .configurable-options {
    form {
      @extend .form-horizontal;

      .configurable {
        @extend .col-md-12;
        @extend .form-group;

        textarea, input[type=text], input[type=password] {
          @extend .form-control;
        }
      }

      input[type=submit] {
        @extend .btn;
        @extend .btn-primary;
      }
    }
  }
}

Just save this into your rails assets and you're ready to go.

Running the Tests

The tests for this rails engine are in the spec and features directories. They use the dummy rails app in spec/dummy

From the top level run:

$ bundle exec rake app:db:schema:load
$ bundle exec rake app:db:test:prepare
$ bundle exec rake

Contributing

All contributions are welcome. Just fork the code, ensure your changes include a test, ensure all the current tests pass and send a pull request.

Copyright

Copyright (c) 2011 Paul Campbell. See LICENSE.txt for further details.

configurable_engine's People

Contributors

aayushkhandelwal11 avatar antoshalee avatar demillir avatar dsgriffin avatar ento avatar jnicklas avatar lilliealbert avatar mendab1e avatar metalelf0 avatar michaelglass avatar pat avatar paulca avatar tjgrathwell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

configurable_engine's Issues

Configuration file name mismatch in Readme

In the readme (web interface section) there is a reference to a behavior.yml configuration file. The file name in the documentation should be configurable.yml.

Thank you for your work, hope this helps.
Davide

This is TERRIBLE

Why would you ever want to do this? It reminds me of working with Drupal where half of the env was in the db and half was in files and you never knew what was what. I wouldn't put any more effort into this, it's a completely non-rails way of doing things IMHO.

Configure controller

Is possible to execute some code after a Configurable record is updated?

I am storing DB credentials, and my application needs to be restarted to take these changes, how could I achieve this?

I have:

class DbSwitch::Ms < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
    :adapter  => Configurable.ms_adapter,
    :host     => Configurable.ms_host,
    :database => Configurable.ms_database,
    :username => Configurable.ms_username,
    :password => Configurable.ms_password,
    :port     => Configurable.ms_port,
    :pool     => Configurable.ms_pool
  )
end

I am using Rails 3, I would like that when some of these variables change this affects Ms class.

But maybe this is more about Rails knowledge.

updated version loses ability to save some changes

I have version 0.2.9 working fine in dev. When I push to Heroku without locking version it gets version 0.4.4. For some reason, the updated version can save numbers and the very first boolean parameter, but toggles to all the later booleans fail to save, although it thinks it worked and gives me a 'changes saved' flash message. Locking the version to 0.2.9 makes everything work again (though I no longer get flash messages). Sorry, I know this probably isn't exactly a true 'issue', but I wonder if there is some trick to updating versions?

Suggestion: clarify "the database"

The README mentions storing settings in "the database". I quickly realized that this is a fake ActiveRecord object that serializes back to config.yml. I see the advantages - simple and easy to edit, lets you make changes at dev-time without a migration - but it means you can't use this if you run multiple application servers, since they won't share the same database.

Might want to clarify that in the README.

BigDecimal issue on ruby-2.6

Got this issue

/home/rof/cache/bundler/ruby/2.6.0/gems/configurable_engine-0.5.0/app/models/configurable.rb:84: warning: BigDecimal.new is deprecated; use BigDecimal() method instead.

How to customize the view?

Nice tool. How can I supply a customized view? And are there any hooks to allow custom validations and so on?

store password encypted

it would be nice if you can specify if you want an item to be encrypted or not for storing passwords.

Instance of class does not behave like ActiveRecord model

The error occur when trying to create a new model using ActiveRecord which hasn't been initialized in the config/configurable.yml file.

Ruby Version: 2.6.6
gem version: 0.4.6

Inside a Rails console:

c = Configurable.new
c.name='evil'
c.value='monkey_patch'
t=Time.now.to_s(:db)
c.created_at=t
c.updated_at=t
c.valid?
 c.valid?
NoMethodError: undefined method `[]' for nil:NilClass
from /home/dev/rails/my_app/vendor/cache/gems/configurable_engine-0.4.8/app/models/configurable.rb:125:in `type_of_value'

Looking at the method reveals the bug, which should be an easy fix:

  def type_of_value
    return unless name
    valid = case Configurable.defaults[name][:type] # raises if  Configurable.defaults[name].nil?
    when 'boolean'
      [true, 1, "1", "true", false, 0, "0", "false"].include?(value)
    when 'decimal'
      BigDecimal(value) rescue false
    when 'integer'
      Integer(value) rescue false
    when 'list'
      value.is_a?(Array)
    else
      true
    end
    errors.add(:value, I18n.t("activerecord.errors.messages.invalid")) unless valid
  end

List type store/read with Rails 4

If I configure an item like this

geoip_whitelist_countries:
  default: []
  type: list
  • it returns a correct [] as the default using Configurable.geoip_whitelist_countries
  • It allows for updating with Configurable.find_or_create_by(name: 'geoip_whitelist_countries').update_attribute(:value, "AF")
    • and returns a correct ["AF"]
  • it allows for updating with Configurable.find_or_create_by(name: 'geoip_whitelist_countries').update_attribute(:value, ["AF", "CH"])
    • and returns a wrong value of [["[\"AF\"", " \"CH\"]"]] where I expect a ["AF", "CH"]
  • it allows for updating with Configurable.find_or_create_by(name: 'geoip_whitelist_countries').update_attribute(:value, "AF,CH")
    • and returns a wrong value of [["AF", "CH"]] (double array wrapping)

It seems the serialisation of the array does not work, a single value is stored a single string, an array is stored as escaped string and the return value is always wrapped in an array.

I'd expect the code to store and load arrays of values the way rails does this.

Is there something I missed from the documentation about the list type?

Thanks.

Feature request: Add regex validation in configurable.yml

Hi,

I'd like to propose adding validation field in configurable.yml. The benefit of doing this is to avoid run time errors due to invalid configuration value. I'm thinking this can start with simple regex validation on string input, as this is where validation is most useful. Example use cases would be validating email addresses, URLs, time format, etc.

I'm happy to discuss this feature further and maybe take a stab at it.

mass-assignment protection when trying to change a setting.

Hi,

See the ouput I am getting:

Configurable.site_title = 'asd'
  Configurable Load (0.1ms)  SELECT `configurables`.* FROM `configurables` WHERE `configurables`.`name` = 'site_title' LIMIT 1
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name, value

How can I whitelist just Configureable Model?

README test steps don't seem to create test database

I tried to run through the steps in the README to see the tests pass, but the task app:db:test:prepare doesn't seem to do anything.

traviss-air:configurable_engine tjgrathwell$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
traviss-air:configurable_engine tjgrathwell$ find . | grep sqlite
traviss-air:configurable_engine tjgrathwell$ 
traviss-air:configurable_engine tjgrathwell$ bundle exec rake app:db:schema:load app:db:test:prepare
-- create_table("configurables", {:force=>true})
   -> 0.0099s
-- add_index("configurables", ["name"], {:name=>"index_configurables_on_name"})
   -> 0.0013s
-- initialize_schema_migrations_table()
   -> 0.0028s
-- assume_migrated_upto_version(20110110001344, ["/Users/tjgrathwell/workspace/configurable_engine/spec/dummy/db/migrate", "/Users/tjgrathwell/workspace/configurable_engine/db/migrate"])
   -> 0.0013s
traviss-air:configurable_engine tjgrathwell$ find . | grep sqlite
./spec/dummy/db/development.sqlite3
traviss-air:configurable_engine tjgrathwell$ bundle exec rake
/Users/tjgrathwell/.rvm/rubies/ruby-2.1.2/bin/ruby -S bundle exec cucumber  --profile default
Using the default profile...
..F-

(::) failed steps (::)

Could not find table 'configurables' (ActiveRecord::StatementInvalid)
./app/models/configurable.rb:95:in `method_missing'
./lib/configurable_engine/configurables_controller.rb:10:in `block in update'
./lib/configurable_engine/configurables_controller.rb:9:in `map'
./lib/configurable_engine/configurables_controller.rb:9:in `update'
./features/step_definitions/web_steps.rb:29:in `block (2 levels) in <top (required)>'
./features/step_definitions/web_steps.rb:14:in `with_scope'
./features/step_definitions/web_steps.rb:28:in `/^(?:|I )press "([^"]*)"(?: within "([^"]*)")?$/'
features/admin_configurables.feature:9:in `And I press "Save"'

Failing Scenarios:
cucumber features/admin_configurables.feature:6 # Scenario: Editing Config

1 scenario (1 failed)
4 steps (1 failed, 1 skipped, 2 passed)
0m0.323s

I can work around the problem by running RAILS_ENV=test bundle exec rake app:db:migrate to ensure the configurables table gets created, but it seems like it would be better to figure out why app:db:test:prepare isn't working.

Serializer configuration

We are trying to update from an old version 0.4.8 to the newest for an older application.

It seems the serializer has changed, now for example boolean values are stored as "--- 'false'\n". (yaml).
This breaks other applications which read from the stored database values.

Any change this can be configured or changed? As the model is not namespaced, we can not easily extend it IMHO.

Please release 0.3.1

Hi

The key caching feature in master is not part of version 0.3.0 - could you make another release so that we don't have to use git master? ❤️

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.