Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Created January 7, 2011 19:05
Show Gist options
  • Select an option

  • Save thinkerbot/769940 to your computer and use it in GitHub Desktop.

Select an option

Save thinkerbot/769940 to your computer and use it in GitHub Desktop.
Demonstrates abstraction of columns via a method
require 'rubygems'
require 'fileutils'
require 'active_record'
# >ruby active_record_example.rb
# a
# b
# a.b
# x
# y
# x.y
class Example < ActiveRecord::Base
def three
[one, two].join('.')
end
def three=(value)
one, two = value.split('.', 2)
self.one = one
self.two = two
end
end
#
# Setup
#
database = 'example.sqlite3'
FileUtils.rm(database) if File.exists?(database)
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => database
)
connection = ActiveRecord::Base.connection.raw_connection
connection.execute %q{
create table examples (
id integer primary key,
one varchar2(255),
two varchar2(255)
);
}
#
# Example
#
Example.create(:one => 'a', :two => 'b')
example = Example.find(:first)
puts example.one
puts example.two
puts example.three
# example.update_attributes({:three => 'x.y'})
example.attributes = {:three => 'x.y'}
example.save
example = Example.find(:first)
puts example.one
puts example.two
puts example.three
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment