Skip to content

Instantly share code, notes, and snippets.

@headius
Created November 19, 2012 13:28
Show Gist options
  • Save headius/4110634 to your computer and use it in GitHub Desktop.
Save headius/4110634 to your computer and use it in GitHub Desktop.
Refinements examples for blog post
class Foo
def camelize_string(str)
using Camelize
str.camelize
end
end
using RSpec
describe MyClass do
using RSpec
it "is awesome" do
using RSpec
MyClass.new.should be_awesome
end
end
class Foo
using Camelize
def camelize_string(str)
str.camelize
end
end
using RSpec
describe MyClass do
it "is awesome" do
MyClass.new.should be_awesome
end
end
class Foo
using Camelize
def camelize_string(str)
str.camelize
end
end
end
using RSpec do
describe MyClass do
it "is awesome" do
MyClass.new.should be_awesome
end
end
end
class Yummy
def foo(str)
str.camelize # will error
end
using StringCamelize
def bar(str)
str.camelize
end
end
class Baz < Quux
def up_and_add(str1, str2)
str1.upcase + str2.upcase
end
end
module Camelize
refine String do
def camelize
dup.gsub(/_([a-z])/) { $1.upcase }
end
end
end
class Foo
using Camelize
def camelize_string(str)
str.camelize
end
end
>> Foo.new.camelize_string('blah_blah_blah')
=> "blahBlahBlah"
>> 'blah_blah_blah'.camelize
NoMethodError: undefined method `camelize' for "blah_blah_blah":String
from (irb):17
from /usr/local/bin/irb-2.0.0:12:in `<main>'
class Bar < Foo
def camelize_and_join(str_ary)
str_ary.map {|str| str.camelize}.join(',')
end
end
module BadRefinement
refine String do
def upcase
reverse
end
end
end
class Quux
using BadRefinement
end
class Baz < Quux
def up_and_add(str1, str2)
str1.upcase + str2.upcase
end
end
describe MyClass do
it "is awesome" do
MyClass.new.should be_awesome
end
end
def add_all(str_ary)
str_ary.inject('') do |str, accum|
accum + str
end
end
module WeirdPlus
refine String do
def +(other)
"#{self} plus #{other}"
end
end
end
class MyArray
def initialize
@ary = ['foo', 'bar', 'baz']
end
def inject(accum, &block)
@ary.each do |str|
accum = WeirdPlus.module_exec(str, accum, &block)
end
accum
end
end
def add_all(str_ary)
str_ary.inject('') do |str, accum|
accum + str
end
end
>> add_all(MyArray.new)
=> " plus foo plus bar plus baz"
@wenzowski
Copy link

As of ruby 2.0.0-rc1 refinements have been implemented as file scoped therefore calling using from within a class or module fails.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment