Class: Rubytter

Inherits:
Object
  • Object
show all
Defined in:
lib/rubytter.rb,
lib/rubytter/oauth.rb,
lib/rubytter/version.rb,
lib/rubytter/connection.rb

Direct Known Subclasses

OAuthRubytter

Defined Under Namespace

Classes: APIError, Connection, OAuth

Constant Summary collapse

VERSION =
'1.5.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(login = nil, password = nil, options = {}) ⇒ Rubytter

Returns a new instance of Rubytter.



26
27
28
29
30
# File 'lib/rubytter.rb', line 26

def initialize( = nil, password = nil, options = {})
  @login = 
  @password = password
  setup(options)
end

Instance Attribute Details

#headerObject

Returns the value of attribute header.



24
25
26
# File 'lib/rubytter.rb', line 24

def header
  @header
end

#hostObject

Returns the value of attribute host.



24
25
26
# File 'lib/rubytter.rb', line 24

def host
  @host
end

#loginObject (readonly)

Returns the value of attribute login.



23
24
25
# File 'lib/rubytter.rb', line 23

def 
  @login
end

#path_prefixObject

Returns the value of attribute path_prefix.



24
25
26
# File 'lib/rubytter.rb', line 24

def path_prefix
  @path_prefix
end

Class Method Details

.api_settingsObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/rubytter.rb', line 43

def self.api_settings
  # method name             path for API                    http method
  "
    update_status           /statuses/update                post
    remove_status           /statuses/destroy/%s            post
    #public_timeline         /statuses/public_timeline
    home_timeline           /statuses/home_timeline
    friends_timeline        /statuses/friends_timeline
    #replies                 /statuses/replies
    mentions                /statuses/mentions_timeline
    user_timeline           /statuses/user_timeline
    show                    /statuses/show/%s
    friends                 /friends/list
    followers               /followers/list
    retweet                 /statuses/retweet/%s            post
    retweets                /statuses/retweets/%s
    #retweeted_by_me         /statuses/retweeted_by_me
    #retweeted_to_me         /statuses/retweeted_to_me
    retweets_of_me          /statuses/retweets_of_me
    user                    /users/show
    direct_messages         /direct_messages
    sent_direct_messages    /direct_messages/sent
    send_direct_message     /direct_messages/new            post
    remove_direct_message   /direct_messages/destroy        post
    follow                  /friendships/create             post
    leave                   /friendships/destroy            post
    friendship_exists       /friendships/show
    followers_ids           /followers/ids
    friends_ids             /friends/ids
    favorites               /favorites/list
    favorite                /favorites/create               post
    remove_favorite         /favorites/destroy              post
    verify_credentials      /account/verify_credentials     get
    #end_session             /account/end_session            post
    update_delivery_device  /account/update_delivery_device post
    update_profile_colors   /account/update_profile_colors  post
    limit_status            /application/rate_limit_status
    update_profile          /account/update_profile         post
    #enable_notification     /notifications/follow/%s        post
    #disable_notification    /notifications/leave/%s         post
    block                   /blocks/create                  post
    unblock                 /blocks/destroy                 post
    blocking                /blocks/list                    get
    blocking_ids            /blocks/ids                     get
    saved_searches          /saved_searches/list            get
    saved_search            /saved_searches/show/%s         get
    create_saved_search     /saved_searches/create          post
    remove_saved_search     /saved_searches/destroy/%s      post
    create_list             /lists/create                   post
    update_list             /lists/update                   post
    delete_list             /lists/destroy                  post
    list                    /lists/show
    lists                   /lists/list
    lists_followers         /lists/memberships
    list_statuses           /lists/statuses
    list_members            /lists/members
    add_member_to_list      /lists/members/create           post
    remove_member_from_list /lists/members/destroy          post
    list_following          /lists/subscribers
    follow_list             /lists/subscribers/create       post
    remove_list             /lists/subscribers/destroy      post
  ".strip.split("\n").map{|line| line.strip.split(/\s+/)}
end

Instance Method Details

#__create_saved_searchObject



141
# File 'lib/rubytter.rb', line 141

alias_method :__create_saved_search, :create_saved_search

#__update_statusObject



135
# File 'lib/rubytter.rb', line 135

alias_method :__update_status, :update_status

#create_request(req, basic_auth = true) ⇒ Object



235
236
237
238
239
# File 'lib/rubytter.rb', line 235

def create_request(req, basic_auth = true)
  @header.each {|k, v| req.add_field(k, v) }
  req.basic_auth(@login, @password) if basic_auth
  req
end

#create_saved_search(arg) ⇒ Object



142
143
144
145
# File 'lib/rubytter.rb', line 142

def create_saved_search(arg)
  arg = {:query => arg} if arg.kind_of?(String)
  __create_saved_search(arg)
end

#delete(path, params = {}) ⇒ Object



170
171
172
173
174
175
# File 'lib/rubytter.rb', line 170

def delete(path, params = {})
  path += '.json'
  param_str = to_param_str(params)
  req = create_request(Net::HTTP::Delete.new(path_prefix + path))
  structize(http_request(@host, req, param_str))
end

#direct_message(user, text, params = {}) ⇒ Object



151
152
153
# File 'lib/rubytter.rb', line 151

def direct_message(user, text, params = {})
  send_direct_message(params.merge({:user => user, :text => text}))
end

#get(path, params = {}) ⇒ Object



155
156
157
158
159
160
161
# File 'lib/rubytter.rb', line 155

def get(path, params = {})
  path += '.json'
  param_str = '?' + to_param_str(params)
  path = path + param_str unless param_str.empty?
  req = create_request(Net::HTTP::Get.new(path_prefix + path))
  structize(http_request(@host, req))
end

#http_request(host, req, param_str = nil, connection = nil) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/rubytter.rb', line 217

def http_request(host, req, param_str = nil, connection = nil)
  connection ||= @connection
  res = connection.start(host) do |http|
    if param_str
      http.request(req, param_str)
    else
      http.request(req)
    end
  end
  json_data = JSON.parse(res.body)
  case res.code
  when "200"
    json_data
  else
    raise APIError.new(json_data['error'], res)
  end
end

#post(path, params = {}) ⇒ Object



163
164
165
166
167
168
# File 'lib/rubytter.rb', line 163

def post(path, params = {})
  path += '.json'
  param_str = to_param_str(params)
  req = create_request(Net::HTTP::Post.new(path_prefix + path))
  structize(http_request(@host, req, param_str))
end

#search(query, params = {}) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/rubytter.rb', line 177

def search(query, params = {})
  path = '/search.json'
  param_str = '?' + to_param_str(params.merge({:q => query}))
  path = path + param_str unless param_str.empty?
  req = create_request(Net::HTTP::Get.new(path), false)

  json_data = http_request("#{@search_host}", req, nil, @connection_for_search)
  structize(
    json_data['results'].map do |result|
      search_result_to_hash(result)
    end
  )
end

#search_result_to_hash(json) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/rubytter.rb', line 199

def search_result_to_hash(json)
  {
    'id' => json['id'],
    'text' => json['text'],
    'source' => json['source'],
    'created_at' => json['created_at'],
    'in_reply_to_user_id' => json['to_user_id'],
    'in_reply_to_screen_name' => json['to_user'],
    'in_reply_to_status_id' => nil,
    'user' => {
      'id' => json['from_user_id'],
      'name' => nil,
      'screen_name' => json['from_user'],
      'profile_image_url' => json['profile_image_url']
    }
  }
end

#search_user(query, params = {}) ⇒ Object



191
192
193
194
195
196
197
# File 'lib/rubytter.rb', line 191

def search_user(query, params = {})
  path = '/users/search.json'
  param_str = '?' + to_param_str(params.merge({:q => query}))
  path = path + param_str unless param_str.empty?
  req = create_request(Net::HTTP::Get.new(path_prefix + path))
  structize(http_request(@host, req))
end

#setup(options) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rubytter.rb', line 32

def setup(options)
  @host = options[:host] || 'api.twitter.com'
  @search_host = options[:search_host] || 'search.twitter.com'
  @header = {'User-Agent' => "Rubytter/#{VERSION} (http://github.com/jugyo/rubytter)"}
  @header.merge!(options[:header]) if options[:header]
  @app_name = options[:app_name]
  @connection = Connection.new(options)
  @connection_for_search = Connection.new(options.merge({:enable_ssl => false}))
  @path_prefix = options[:path_prefix] || '/1.1'
end

#structize(data) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/rubytter.rb', line 241

def structize(data)
  case data
  when Array
    data.map{|i| structize(i)}
  when Hash
    class << data
      def id
        self[:id]
      end

      def to_hash(obj = self)
        obj.inject({}) {|memo, (key, value)|
          memo[key] = (value.kind_of? obj.class) ? to_hash(value) : value
          memo
        }
      end

      def method_missing(name, *args)
        self[name]
      end
    end

    data.keys.each do |k|
      case k
      when String, Symbol # String しかまず来ないだろうからこの判定はいらない気もするなぁ
        data[k] = structize(data[k])
      else
        data.delete(k)
      end
    end

    data.symbolize_keys!
  else
    case data
    when String
      CGI.unescapeHTML(data) # ここで unescapeHTML すべきか悩むところではある
    else
      data
    end
  end
end

#to_param_str(hash) ⇒ Object

Raises:

  • (ArgumentError)


283
284
285
286
# File 'lib/rubytter.rb', line 283

def to_param_str(hash)
  raise ArgumentError, 'Argument must be a Hash object' unless hash.is_a?(Hash)
  hash.to_a.map{|i| i[0].to_s + '=' + CGI.escape(i[1].to_s) }.join('&')
end

#update(status, params = {}) ⇒ Object



147
148
149
# File 'lib/rubytter.rb', line 147

def update(status, params = {})
  update_status(params.merge({:status => status}))
end

#update_status(params = {}) ⇒ Object



136
137
138
139
# File 'lib/rubytter.rb', line 136

def update_status(params = {})
  params[:source] = @app_name if @app_name
  __update_status(params)
end