Skip to content

Instantly share code, notes, and snippets.

@dchelimsky
Created July 15, 2011 16:33
Show Gist options
  • Save dchelimsky/1085028 to your computer and use it in GitHub Desktop.
Save dchelimsky/1085028 to your computer and use it in GitHub Desktop.
assign temporary value to an attribute
with_attribute(SomeModel, :record_timestamps).temporarily(false) do
model_instance.update_attributes(:updated_at => 35.minutes.ago)
end
with_attribute(SomeModel, :record_timestamps, false) do
model_instance.update_attributes(:updated_at => 35.minutes.ago)
end
SomeModel.with(:record_timestamps, false) do # with, with_temp, with_attr???
model_instance.update_attributes(:updated_at => 35.minutes.ago)
end
# would be great if we could do something like this, but how??????
SomeModel.record_timestamps.temporarily(false) do
model_instance.update_attributes(:updated_at => 35.minutes.ago)
end
@booch
Copy link

booch commented Aug 19, 2011

My preference would be:

SomeModel.with(:record_timestamps => false) {}

But I'm not sure about polluting Object's namespace with with, so this might be the better option:

with(SomeModel, :record_timestamps => false) {}

Either of these would allow redefining multiple methods at once, which might come in handy on occasion.

I think with is a decent name -- other languages use it for the same thing.

@booch
Copy link

booch commented Aug 19, 2011

So what we're doing here is really just stubbing out a method, but only within the block. If RSpec's Object#stub method didn't already take a block (to define the value of the stubbed method dynamically/lazily), then we could do this:

SomeModel.stub(:record_timestamps => false) { ... do something ... }

So maybe we should use a variant of stub:

SomeModel.stub(:record_timestamps => false).within { ... do something ... } # Just unstub the methods after running the within block?
SomeModel.stub_within_block(:record_timestamps => false) { ... do something ... }

NOTE: I just looked at the RSpec code, and it seems to support the hash syntax I'm using here, but it's not documented.

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