Skip to content

Instantly share code, notes, and snippets.

View vsavkin's full-sized avatar

Victor Savkin vsavkin

View GitHub Profile
@vsavkin
vsavkin / posts_and_comments.rb
Created March 26, 2012 02:07
Create Posts and Comments
blog = Blog.create
post = blog.make_post text: 'great post', location_country: 'Canada', location_city: 'Toronto'
post.make_comment text: 'great comment', location_country: 'Canada', location_city: 'Toronto'
@vsavkin
vsavkin / blog.rb
Created March 26, 2012 02:09
Blog
class Blog < ActiveRecord::Base
...
def all_posts_from country, city
...
end
def all_comments_from country, city
...
end
@vsavkin
vsavkin / location_presenter.rb
Created March 26, 2012 02:09
Location Presenter
class LocationPresenter
def initialize country, city
...
end
end
@vsavkin
vsavkin / location.rb
Created March 26, 2012 02:10
Location
class Location < Struct.new(:country, :city)
end
@vsavkin
vsavkin / refactored_post.rb
Created March 26, 2012 02:11
Refactored Post
class Post < ActiveRecord::Base
composed_of :location, mapping: [%w(location_country country),
%w(location_city city)]
def self.all_posts_from location
Post.where location: location
end
end
@vsavkin
vsavkin / making_post.rb
Created March 26, 2012 02:12
Making a Post
blog.make_post text: 'great post 2', location: Location.new('Canada', 'Toronto')
@vsavkin
vsavkin / testing_post.rb
Created March 26, 2012 02:13
Testing Post
def Toronto
Location.new('Canada', 'Toronto')
end
...
blog.make_post text: 'great post', location: Toronto
@vsavkin
vsavkin / location_ar.rb
Created March 26, 2012 02:13
Location AR
class Location < ActiveRecord::Base
validates :city, :uniqueness => {:scope => :country}
def self.get country, city
location = Location.find_by_country_and_city(country, city)
raise "There is no '#{city}' in '#{country}'" unless location
location.readonly!
location
end
@vsavkin
vsavkin / using_location_ar.rb
Created March 26, 2012 02:14
Using Location AR
toronto = Location.get('Canada', 'Toronto')
blog.make_post text: 'great post 2', location: toronto
@vsavkin
vsavkin / restrict_ar.rb
Created April 15, 2012 16:10
Restrict AR
# The User class has two attributes: name and age.
# STEP 1: Call restrict_ar! inside your model definition. It will make most AR methods private.
class User < ActiveRecord::Base
restrict_ar!
end
# All AR class methods will become private. As a result, the following calls will raise an exception:
User.create! # BOOM