简体   繁体   中英

Classes, methods and variables in ruby

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"

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM