A little module add-on (For Scripters)
#1
A little module add-on (For Scripters)
Say hello to attr_sec_accessor
by Zeriab
Oct 13 2007

This is a locked, single-post thread from Creation Asylum. Archived here to prevent its loss.
No support is given.


Here's a litte addition to the module I have made ^^
Code

Simple Version


You can use it like this:
Code:
attr_sec_accessor :method, default

It works pretty much like the attr_accessor except that you can only do method creation per call.
method is the method name.
default is the default value the method returns. (If it has not been written to yet.)

An usage example:
Code:
class Foo
  attr_sec_accessor :visible, false
  attr_sec_accessor :data, 'Data_Foo.new'
end


This way you'll have that the default variable of visible is false.
If it is called before you write to the variable you will get 'false' rather than 'nil'
One thing to note is that lazy instantiation is used.
Let us assume that Data_Foo is a heavy object. It is only created if you try to read what the data attribute contains before you have written to it. More specifically. If the value of data attribute is nil then it is change to be what the default value is.

The code in the example is converted to this:
Code:
class Foo
  def visible=(value)
    @visible = value
  end
  def visible
    @visible = false  if @visible.nil?
    @visible
  end
  
  def data=(value)
    @data = value
  end
  def data
    @data = Data_Foo.new  if @data.nil?
    @data
  end
end

One thing to notice is that you must put '' around Data_Foo.new to make it a string. Otherwise you will get an error in almost all cases.

The greatest use will probably be if you want to add information to hidden classes. Let's for an example take RPG::Actor.
You can use its initialize method to set the default value by default because it won't be called automatically.
Other than that it will hopefully make the coder shorter and easier to understand.

Naturally. Only use this functionality where it is needed or where it can have a positive use ^_^

*hugs*
~ Zeriab
[Image: ZeriabSig.png]
}


Possibly Related Threads…
Thread Author Replies Views Last Post
  New Faster Input module azrith001 0 2,346 09-02-2008, 01:00 PM
Last Post: azrith001



Users browsing this thread: 1 Guest(s)