开发者

Creating a simple ruby gem that allows the user to call a defined method?

开发者 https://www.devze.com 2023-04-10 16:44 出处:网络
I\'ve been looking for some tutorials on creating ruby gems, but all seem to be overly complicated. Essentially, all I want is to make a gem that (trivial example alert) allows the user to place a met

I've been looking for some tutorials on creating ruby gems, but all seem to be overly complicated. Essentially, all I want is to make a gem that (trivial example alert) allows the user to place a method add_one(x) in their code, once the gem is installed.

A lot of tutorials explain how you can call the gem's methods with Classname.method(), but that's really not what I want. RyanB has a good example here, but again I can't get it to work - mainly because of the 3 lines of code at the bottom of uniquify.rb that read.

class ActiveRecord::Base
  include Uniquify
end

In my case, my main module is called AddOne, so how would I go about doing this? Again, sorry for the trivial example, I'm just looking to get started so that my gems will allow the user to call plain ol' methods, without specifying Modules or Classes. In Ryan's exampl开发者_JS百科e, he's able to simple call uniquify() in the code.


In the example given, he can call uniquify as a method because he is calling it inside a class which includes ActiveRecord::Base. (He calls uniquify inside the class Product < ActiveRecord::Base...end block) There isn't any real magic here.

To my understanding, what you desire is easily achievable, but isn't a good idea, 'best practice' considered. You can define anything you want in your gem. For instance, I could package a file called say_hello.rb inside a gem called salutations.

say_hello.rb

def say_hello
  puts "Hello everybody"
end

By requiring the packaged gem salutations I would gain access to anything defined therein. However, it might lead to unexpected consequences. Do what you need to do, but just understand that it might not be the best idea. Hence, you build things into classes or modules to contain them, and to prevent conflicts with other code. Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号