Skip to content

Instantly share code, notes, and snippets.

@mmrwoods
Last active January 1, 2016 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmrwoods/8100949 to your computer and use it in GitHub Desktop.
Save mmrwoods/8100949 to your computer and use it in GitHub Desktop.
Create writer methods for active model human attribute names. Useful when importing from spreadsheets.
module Importing
module HumanAttributeNameWriters
def self.included(base)
base.new # Force activerecord to initialize attributes
# only allow accessible attributes that are not foreign keys or nested attributes
foreign_keys = Agent.reflect_on_all_associations.map(&:association_foreign_key)
allowed_attributes = base.accessible_attributes.select do |name|
name.present? && !foreign_keys.include?(name) && !name.match(/_attributes$/)
end
# alias each allowed attr writer with a human name version and make accessible
allowed_attributes.each do |name|
base.class_eval {
alias_method "#{base.human_attribute_name(name)}=", "#{name}="
attr_accessible "#{base.human_attribute_name(name)}"
}
end
end
end
end
require 'fast_spec_helper'
require 'active_record'
require 'nulldb/core'
require 'importing/human_attribute_name_writers'
require 'active_support/core_ext/string/inflections'
describe "Importing::HumanAttributeNameWriters" do
before(:all) do
if ActiveRecord::Base.connected?
@connection_config_before = ActiveRecord::Base.connection_config
end
ActiveRecord::Base.establish_connection :adapter => :nulldb
end
after(:all) do
if @connection_config_before
ActiveRecord::Base.establish_connection(@connection_config_before)
end
end
class AModel < ActiveRecord::Base
end
describe AModel do
context "with an attribute" do
before(:all) do
ActiveRecord::Base.connection.create_table "a_models" do |t|
t.string :an_attribute
end
end
context "when not marked as accessible" do
context "including HumanAttributeNameWriters" do
before(:all) do
AModel.class_eval{ include Importing::HumanAttributeNameWriters }
end
it "should not create a human attribute name writer" do
AModel.new.should_not respond_to("An attribute=")
end
end
end
context "when marked as accessible" do
before(:all) do
AModel.class_eval { attr_accessible :an_attribute }
end
context "including HumanAttributeNameWriters" do
before(:all) do
AModel.class_eval{ include Importing::HumanAttributeNameWriters }
end
it "should create a human attribute name writer" do
AModel.new.should respond_to("An attribute=")
end
context "and the human attribute name writer" do
it "should set the value of the real attribute" do
subject.send("An attribute=", "foo")
subject.an_attribute.should == "foo"
end
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment