Skip to content

Instantly share code, notes, and snippets.

@Olgagr
Olgagr / Comparable.rb
Created May 26, 2013 08:26
Comparable module in Ruby
#to use this module the class has to mixin it and define <=> method
class Bid
include Comparable
attr_accessor :estimate
def <=>(other_bid)
if self.estimate > other_bid.estimate
1
@Olgagr
Olgagr / case_statement_behaviour.rb
Created May 26, 2013 08:45
Defining case statement behaviour for Ruby class
# to do it we have to define === method inside our class
class Ticket
attr_accessor :venue, :date, :price
def initialize(venue, date, price)
self.venue = venue
self.date = date
self.price = price
@Olgagr
Olgagr / devise_setup_email_layout.rb
Created May 28, 2013 18:54
Set up layout for email in Devise gem
# in application.rb
config.to_prepare do
Devise::Mailer.layout "email_template" # in views/layouts
end
@Olgagr
Olgagr / rspec_shared_examples.rb
Created May 30, 2013 06:00
create shared examples in spec file
shared_examples('title of shared examples') do
#some examples here
end
#then in a spec
describe 'something' do
it_behaves_like 'title of shared examples'
@Olgagr
Olgagr / short_syntax_factory_girl.rb
Created June 2, 2013 07:09
shorter syntax for factory_girl
# in spec_helper
RSpec.configure do |config| do
#other code
config.include FactoryGirl::Syntax::Methods
end
@Olgagr
Olgagr / controller_private_setter_for_local_variable.rb
Created June 15, 2013 15:48
Controller private setter for local variable
class FollowingRelationshipsController < ApplicationController
def create
current_user.follow user
redirect_to user
end
def destroy
current_user.unfollow user
redirect_to user
@Olgagr
Olgagr / set_partial_path_in_class.rb
Created June 15, 2013 16:43
Set partial path in the class which does not inherit fro active model
class Timeline
extend ActiveModel::Naming # it's better approach
def initialize(user)
@user = user
end
def to_partial_path
'path/to/partial' # but there is a better way(see above)
@Olgagr
Olgagr / launchy_open_page.rb
Created June 23, 2013 14:35
Using launchy gem in integration tests
# integration tests...some code
save_and_open_page
# integration tests...some code
@Olgagr
Olgagr / lookahead_lookbehind_assertions
Created July 14, 2013 15:57
Lookahead and Lookbehind Assertions
# Lookahead assertion
str = "123 456. 789"
m = /\d+(?=\.)/.match(str) # m[0] = '456'. Period doesn't count as a part of the match
/\d+(?!\.)/ # negative lookahead
# Lookbehind assertion
str = "David BLACK"
m = /(?<=David )BLACK/ # only match BLACK if it's preceded by 'David'
/(?<!David) BLACK/ # negative lookbehind
@Olgagr
Olgagr / match_but_dont_capture
Created July 14, 2013 16:01
Construct to match something but don't count it as a capture
str = 'abc def ghi'
m = /(abc) (?:def) (ghi)/.match str
# m[0] -> abc
# m[2] -> ghi