How do I inherit default data from a module or class
I am working on an application to automate testing for SQL injection vulnerability. It is currently named Deft and is for a University project.
I want to be able to run tests from a command line, or an interactive console. I am coding several classes. (Deft::Cli
, Deft::Console
etc.)
Here's what I think I'd like to do.
module Deft
module App
开发者_JS百科 attr_accessor :origin
@origin = { "host" => "localhost", "port" => "80" }
end
end
module Deft
class Console
include App
def initialize
puts origin
end
end
end
The example has been simplified, but the point is that the default values (and structure) get defined in the Deft::App
module.
The problem as I can tell is that although methods.grep(/origin/)
from inside a console instance does indeed give me ["origin=", "origin"]
calling origin
returns nil
. Instead of the values I define in Deft::App
. It makes sense that it doesn't work, but I don't know how to make it work.
Perhaps I'm taking the simplified example too literally, but one way to fix it is to get rid of the attr_accessor
class method invocation and just make origin
be the constant Origin
or ORIGIN
.
What about this?
module Deft
class DefaultConsole
attr_accessor :origin
def initialize
@origin = {'host' => 'localhost', 'port' => 80}
end
end
class Console < DefaultConsole
def initialize
super
puts origin
end
end
end
Deft::Console.new
# => {'host' => 'localhost', 'port' => 80}
Try like this:
module Deft
module App
attr_accessor :origin
def init
@origin = { "host" => "localhost", "port" => "80" }
end
end
end
module Deft
class Console
include App
def initialize
init
puts origin
end
end
end
Deft::Console.new
Thanks to everyone that added their input. I'm going to go ahead and answer my own question, this works as I had hoped.
module Deft
module App
@@origin = { "host" => "localhost", "port" => "80" }
def origin ; @@origin ; end
def origin=(args) ; @@origin=(args) ; end
end
end
If anyone wants to copy and clean this up using attr_accesor then I'd be happy to edit this back into my question and accept their answer.
精彩评论