The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
attributes with default values (on steroids)

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Matt Williams

Posts: 466
Nickname: aetherical
Registered: Feb, 2008

Matt Williams is a jack-of-all trades living in Columbus, OH.
attributes with default values (on steroids) Posted: May 8, 2008 11:19 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Matt Williams.
Original Post: attributes with default values (on steroids)
Feed Title: Ruby Blender
Feed URL: http://feeds2.feedburner.com/RubyBlender
Feed Description: This blog contains short-ish ruby tips, hints, and techniques.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Matt Williams
Latest Posts From Ruby Blender

Advertisement

While ruby has attr_accessor there's no good way to specify a default value which comes as part of the stock language. Thank goodness for metaprogramming. Based off of Create getter and setter on a valorized variable, I have a solution which takes either a value or a block as the default. It's based, in part, upon my solution for Ruby Quiz #67 Metakoans.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class Object
  def self.attribute(*arg,&block)
    (name,value) = arg
    self.send(:define_method, name) {
      if instance_variables.include? "@#{name}"
           self.instance_eval "@#{name}"
      else
        if block_given?
          instance_eval &block
        else
          value
        end
      end
    }
    self.send(:define_method, "#{name}="){ |value|
      self.instance_eval "@#{name} = value"
    }
  end
end

Given the following class:

1
2
3
4
5
6

class Foo
  attribute :bar
  attribute(:fud) {instance_variables.include?("@bar") ? @bar : ' '}
  attribute :fi, 10
end

we can test as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

>>   t=Foo.new
=> #<Foo:0xb7b9cadc>
>> t.bar
=> nil
>> t.fud
=> " "
>> t.fi
=> 10
>> t.bar = 5
=> 5
>> t.fud
=> 5
>> t.fud = 20
=> 20
>> t.fud
=> 20
>> 

I imagine it can be simplified some more, but it works, and I think it's kinda nifty.....

Read: attributes with default values (on steroids)

Topic: Using the Ruby Librarian - a step-by-step guide Previous Topic   Next Topic Topic: Using Stubs to Capture Test Essence

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use