Skip to content

Instantly share code, notes, and snippets.

@andreypronin
Created May 15, 2013 19:13
Show Gist options
  • Save andreypronin/5586511 to your computer and use it in GitHub Desktop.
Save andreypronin/5586511 to your computer and use it in GitHub Desktop.
HStore accessor: Postgres, Rails
def hstore_get(field_name)
method(field_name).call
end
def hstore_set(field_name,value)
method("#{field_name}=").call(value)
end
def hstore_accessor(field_name,name)
define_method(name) do
hstore = hstore_get(field_name)
hstore && hstore[name]
end
define_method("#{name}=") do |value|
hstore = hstore_get(field_name) || {}
hstore_set field_name, hstore.merge( name => value )
end
define_method("#{name}_present?") do
hstore = hstore_get(field_name)
hstore && hstore.has_key?(name)
end
end
class CreateXxx < ActiveRecord::Migration
def change
create_table :xxxs do |t|
t.hstore :params
end
add_index "xxxs", ["params"], name: "xxxs_gin_params", using: :gin
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment