Reputation: 65143
I have a class defined in a gem by
Diff::LCS
and I want to add some methods to it, so I figured I would extend it.
Now, I've extended object before just by defining:
class Object
in object.rb (in my lib/ folder in my rails project)
now, my file where I do
class Diff::LCS
(in attempt to extend it)
is called diff_lcs.rb, again in lib/.
Do I need to match the same folder structure as the gem in order to extend it properly?
How do I extend a Class::SubClass thing?
EDIT: added code
test/unit/diff_lcs_test.rb:
#tests lib/diff_lcs.rb
require "test/unit"
require 'diff/lcs'
require 'diff/lcs/string'
require File.expand_path(File.dirname(__FILE__) + "/../../lib/diff_lcs")
# require '../../lib/diff_lcs.rb'
class DiffLCSTest < Test::Unit::TestCase
def correctly_display_inlineness
@source_text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit..."
@new_text = "lorem ipsUm sit [amet]!, COnsectetur adipisicing elit i have no idea what I'm doing..."
return false
end
end
lib/diff_lcs.rb:
class Diff::LCS
REMOVED_OPEN = "{*[}"
REMOVED_CLOSE = "{]*}"
ADDED_OPEN = "{*(}"
ADDE_CLOSE = "{)*}"
def self.apply_diff_inline(source_text, new_text)
result = ""
operations = ["-", "+"]
diffs = diff(source_text, new_text)
operations.each do |current_operation|
end
return result
end
end
Error:
> bundle exec ruby test/unit/diff_lcs_test.rb
$ APP_PATH/lib/diff_lcs.rb:1: LCS is not a class (TypeError)
Upvotes: 1
Views: 566
Reputation: 160191
All you need to do is re-open the class, as you're doing (assuming that's the correct class name).
You do need to make sure the library is being included/required, however. (The specifics depend on the Rails version.)
Upvotes: 0
Reputation: 27747
Do you mean "reopen" the class (instead of extend)? If so - you should be able to do exactly what you've just said.
class Diff::LCS
def my_new_method
...
end
end
However - you have to beware of load-order. If the place that you have written the above code is loaded before your original Diff:LCS class is loaded - then you'll not be reopening, but actually defining the class.
...ah, just re-read your issue. You're trying to figure out what to name the file in which you put this. Previously you have depended on rails' default naming convention (eg Object being in object.rb) but you don't have to do that. you can actually just call it "whatever_library.rb" as long as you manually load it (using include "whatever_library.rb"
) in your environment.rb (in Rails2) (or I think application.rb for Rails3).
If you must use rails default then yes, make a directory called "diff", and in there, put your code in the "lcs.rb" file.
Upvotes: 2