0

I am trying to write a plug-in system in ruby and I am running into a bit of trouble with never having learned a good set of fundamentals. Anyway my plug-in system is just an experiment in working with classes. My Plugin class looks like this:

class Plugin
  def info
    # Set some default values when a new class is created.
    name = "Test Plugin"
    description = "Just a simple test plugin."
    version = "1.0"
  end
end

In a plugin I would require the above file and write some code like so:

require "./_plugin_base.rb"

pluginCleanup = Plugin.new

pluginCleanup.info do
  name = "Cleanup"
  description = "Remove the files we don't need in the public folder."
  version = "1.0"
end

Now, I know this code does not work. Basically what I think I want are instance variables under the info method. I have tried using true instance variables and they do work well however I want to keep these inside the info function if that makes any sense., because when I do use attr_accessor the varibles are accessable as:

pluginCleanup.name = "New Value"

Can someone tell me how I would make the code work as described in the examples above? I just want to be able to declare a new instance and call:

pluginCleanup.info.name = "New Value"

2 Answers 2

2

What do you think of this?

class Plugin
  def initialize
    @info = PluginInfo.new
  end

  attr_reader :info
end

class PluginInfo
  def initialize
    # Set some default values when a new class is created.
    @name = "Test Plugin"
    @description = "Just a simple test plugin."
    @version = "1.0"
  end

  attr_accessor :name, :description, :version
end

plugin_cleanup = Plugin.new
 #=> #<Plugin:0x000000024f0c48 @info=#<PluginInfo:0x000000024f0c20 @name="Test Plugin", @description="Just a simple test plugin.", @version="1.0">> 
plugin_cleanup.info.name
 #=> "Test Plugin"
plugin_cleanup.info.name = "A New Plugin"
 #=> "A New Plugin"
plugin_cleanup.info.name
 #=> "A New Plugin"
Sign up to request clarification or add additional context in comments.

2 Comments

Good application for namespacing: Plugin and Plugin::Info
Hmm that looks good, I'm going to try and see if I can use namespacing like zetetic said.
0

I think using instance_eval may help, like in the following example

class Panda
  def self.feed(&block)
    panda = Panda.new
    panda.instance_eval(&block)
  end

  def nom(food)
    puts "nomming #{food}"
  end
end

Panda.feed do
  nom :bamboo
  nom :chocolate
end

You'll have to adapt it a bit to your needs, but I'm just indicating that it's possible to do it. Let me know if you get stuck.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.