Ivan Stana
Ivan Stana

Reputation: 656

Other ways to "embed" or make variable "static" in new method?

Is there any other ways to make it another way than with closure and define_method?

Say i have this:

def test
  result=[1,2,3]
  metadata=['foo', 'bar'] # for simplicity, could be fetched from database
  result.define_singleton_method :headers, lambda { metadata }
  result
end

I'm curious, are there other ways to embed, make static or well, "copy" metadata variable into method in Ruby?

Upvotes: 1

Views: 80

Answers (2)

Joshua Cheek
Joshua Cheek

Reputation: 31756

I find it kind of iffy to be defining methods like this (probably you should have an object that looks like an array rather than making the array look like your object), but this will work as well.

def test
  result=[1,2,3]
  result.instance_eval { @headers = ['foo', 'bar'] }
  result.define_singleton_method(:headers) { @headers }
  result
end

You could also do something like this (it's a little different in that it creates a setter as well).

module HasHeaders
  attr_accessor :headers
end

def test
  result = [1,2,3].extend HasHeaders
  result.headers = ['foo', 'bar']
  result
end

Upvotes: 1

Matheus Moreira
Matheus Moreira

Reputation: 17030

Well, method definitions aren't closures, so this will not work:

def result.headers
  metadata
end

Since you are testing, I recommend stubbing the method. With RSpec::Mocks:

result.stub(:headers).and_return metadata

Related:

Upvotes: 0

Related Questions