开发者

Is there a gem to manage settings per resource?

开发者 https://www.devze.com 2023-03-24 03:35 出处:网络
I need a gem that can abstract resource setting management. Basically I want something like @person = Person.find(1)

I need a gem that can abstract resource setting management. Basically I want something like

@person = Person.find(1)
@person.settings <- this gives a hash of key/value pairs associated with this resource

I a开发者_如何学编程lso need a way to have "default" settings per Person as well as a way to override those for specific @person. The settings should be persisted in SQL db.


This is an old plugin but it's pretty full featured and I've used it in a number of different projects: has_easy

For Rails3 the generator won't work but you can just create the migration it needs by hand.

class CreateHasEasyThings < ActiveRecord::Migration
  def self.up
    create_table :has_easy_things do |t|
      t.string  :model_type, :null => false
      t.integer :model_id, :null => false
      t.string  :context
      t.string  :name, :null => false
      t.string  :value
      t.timestamps
    end
  end

  def self.down
    drop_table :has_easy_things
  end
end

Basically the way it works is that you can associate any model you want with this object and it will store preferences, settings or really pretty much anything that can be serialized by Rails.

You define your settings or what have you on the model:

class User < ActiveRecord::Base
  has_easy :settings do |p|
    p.define :language
    p.define :theme
  end
  has_easy :flags do |f|
    f.define :is_admin
    f.define :is_spammer
  end
end

which dynamically creates a bunch of methods for accessing settings and flags.

u = User.new
u.settings.language = 'en/us'
u.flags.is_admin = true


If you have rails 2 or rails 3, check out Ledermann's rails-settings gem which has a syntax to get all key-value pairs just like you asked for:

    son.settings.all

Easy to add settings:

    son.settings.key = value

You also get activerecord scopes to search based on settings. And you can set default settings and global (application scope) settings.

For rails 2, you need to use version "~> 1.x" and follow docs: https://github.com/ledermann/rails-settings/blob/c5c34faf1bbe5742b58f6b3acff3874edc6e4bbc/README.md

If you need :before and :after event handling, check https://github.com/exceed/preferential/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号