[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Creating a plugin based app

Kimmo Lehto

5/26/2008 9:56:00 AM

Any ideas how to do something like this..?

I'd like to drop new parsers into a plugin-directory of my app without
making modifications to the main app, so there would be something like:

# main.rb:
require 'plugins/*'
parsed_data = Parser.parse_data(data_goes_here)

# plugins/foo.rb:
class FooParser < Parser
handles /^foo/
def parse_data(data)
data.do_something if data.match(@handles)
end
end

# plugins/bar.rb:
class BarParser < Parser
handles /^bar/
def parse_data(data)
data.do_something if data.match(@handles)
end
end

Then if I wanted to add a new parser i would just throw it in there with
the rest. Perhaps some sort of "register_handler"-call in each plugin?
--
Posted via http://www.ruby-....

2 Answers

Jesús Gabriel y Galán

5/26/2008 10:16:00 AM

0

On Mon, May 26, 2008 at 11:56 AM, Kimmo Lehto <kimmo.lehto@gmail.com> wrote:
> Any ideas how to do something like this..?
>
> I'd like to drop new parsers into a plugin-directory of my app without
> making modifications to the main app, so there would be something like:
>
> # main.rb:
> require 'plugins/*'
> parsed_data = Parser.parse_data(data_goes_here)
>
> # plugins/foo.rb:
> class FooParser < Parser
> handles /^foo/
> def parse_data(data)
> data.do_something if data.match(@handles)
> end
> end
>
> # plugins/bar.rb:
> class BarParser < Parser
> handles /^bar/
> def parse_data(data)
> data.do_something if data.match(@handles)
> end
> end
>
> Then if I wanted to add a new parser i would just throw it in there with
> the rest. Perhaps some sort of "register_handler"-call in each plugin?

I think you already have it. The "handles" method could be implemented
to register every handler, and then instantiate a child parser based on
which handler the data matches. You would need to move the "if data.match..."
part to the parent Parser class. Something like:

class Parser
@handlers = {}
class << self
attr_accessor :handlers

def handles reg
Parser.handlers[reg] = self
end

def parse_data data
handler = @handlers.keys.find {|x| data.match(x)}
raise "No parser found for #{data}" unless handler
parser = @handlers[handler]
parser.new.parse_data data
end
end
end


class FooParser < Parser
handles /^foo/

def parse_data data
puts "FooParser parsing #{data}"
end
end

class BarParser < Parser
handles /^bar/
def parse_data data
puts "BarParser parsing #{data}"
end
end

Hope this helps,

Jesus.

Kimmo Lehto

5/26/2008 10:35:00 AM

0

Jesús Gabriel y Galán wrote:
> Hope this helps,

Perfect, thanks.
--
Posted via http://www.ruby-....