How to define a method in a Gem
I am creating a Gem that for Rails that includes JQuery helpers and I want to do something like this in my view:
JQueryCheats::HoverImage.mouseoverimage("开发者_开发知识库image1.jpg","image2.jpg")
I have pretty much the following setup:
module JQueryCheats
class HoverImage
#class used to do a quick Hover image
attr_accessor :image_tag
def initialize()
end
def mouseoverimage(initimage,hoverimage)
@image_tag =""
@image_tag = "<img src=\"#{initimage}\" alt=\"image\" onmouseover=\"$(this).attr('src','#{hoverimage}')\" onmouseout=\"$(this).attr('src','#{initimage}')\">"
return @image_tag
end
end
end
but that doesn't work, I am really new at making Gems and could use some help
Sounds like you want a class method.
You can do this with the self keyword.
module JQueryCheats
class HoverImage
attr_accessor :image_tag
def initialize()
end
def self.mouseoverimage(initimage,hoverimage) #Note the self
@image_tag =""
@image_tag = "<img src=\"#{initimage}\" alt=\"image\" onmouseover=\"$(this).attr('src','#{hoverimage}')\" onmouseout=\"$(this).attr('src','#{initimage}')\">"
return @image_tag
end
end
end
For defining more than one of these methods, I would use the class << self method mentioned by @Travis instead of prepending self to all of your methods. Both perform the same task.
class << self
def mouseoverimage(initimage, hoverimage)
end
end
For completeness, there is another method using the class name before the definition, however using this makes refactoring more difficult as you have to change it in more than one place if you rename your class.
def HoverImage.mouseoverimage(initimage,hoverimage)
When I was looking at the mini_magick gem I noticed they had class << self
in their code wrapped arround their methods, so I tried that right after attr_accessor I wrapped the two methods in class << self
and everything worked as expected.
So now the code is:
module JQueryCheats
class HoverImage
#class used to do a quick Hover image
attr_accessor :image_tag
class << self
def mouseoverimage(initimage,hoverimage)
@image_tag =""
@image_tag = "<img src=\"#{initimage}\" alt=\"image\" onmouseover=\"$(this).attr('src','#{hoverimage}')\" onmouseout=\"$(this).attr('src','#{initimage}')\">"
return @image_tag.html_safe
end
def initialize()
end
end#end self
end
end
精彩评论