如何将以下ruby代码转换为Rails插件?

时间:2009-08-09 08:27:40

标签: ruby-on-rails ruby-on-rails-plugins bit.ly

#!/opt/ruby_ee/bin
    require 'rubygems'
    require 'twitter'
    require 'net/http'
    require 'uri'
    require 'httparty'
    module FbTweet

        def FbTweet.tweet(url)
            bitly_url = Bitly.shorten(url)
            httpauth = Twitter::HTTPAuth.new('username', 'password')
            base = Twitter::Base.new(httpauth)
            base.update("Testing to port this into rails plugin #{bitly_url}")
            base.friends_timeline.each { |tweet| puts tweet.text }
        end

        class Bitly
            include HTTParty
            base_uri 'api.bit.ly'
            basic_auth 'millisami', 'R_sadfdsfwefsdf2323fafasd'
            format :json
            def self.shorten(url)
                response = get('/shorten', :query => required_params.merge(:longUrl => url))
                response['results'][url]['shortUrl']
            end
            def self.required_params
                {:version => "2.0.1"}
            end
        end

    end
    puts "Calling twitter to test.."
    puts FbTweet.tweet("http://google.com")

1 个答案:

答案 0 :(得分:2)

只需创建一个插件骨架

  

./ script / generate plugin FbTweet

然后在RAILS_ROOT / vendor / plugins / fb_tweet / lib / fb_tweet.rb文件中放入代码的内容:

  require 'rubygems'
    require 'twitter'
    require 'net/http'
    require 'uri'
    require 'httparty'
    module FbTweet

            def FbTweet.tweet(url)
                    bitly_url = Bitly.shorten(url)
                    httpauth = Twitter::HTTPAuth.new('newnepal', 'wnn_tweet_pwd')
                    base = Twitter::Base.new(httpauth)
                    base.update("Testing to port this into rails plugin #{bitly_url}")
                    base.friends_timeline.each { |tweet| puts tweet.text }
            end

            class Bitly
                    include HTTParty
                    base_uri 'api.bit.ly'
                    basic_auth 'millisami', 'R_fca41718b34e48a06daf0260c5919cf0'
                    format :json
                    def self.shorten(url)
                            response = get('/shorten', :query => required_params.merge(:longUrl => url))
                            response['results'][url]['shortUrl']
                    end
                    def self.required_params
                            {:version => "2.0.1"}
                    end
            end

    end

现在,打开你的控制台,只需输入:

FbTweet.tweet( “www.example.com”)