repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
mislav/twitter
lib/twitter/authenticatable.rb
<reponame>mislav/twitter<gh_stars>1-10 module Twitter module Authenticatable # Credentials hash # # @return [Hash] def credentials { :consumer_key => consumer_key, :consumer_secret => consumer_secret, :token => oauth_token, :token_secret => oauth_token_secret, } end # Check whether credentials are present # # @return [Boolean] def credentials? credentials.values.all? end end end
mislav/twitter
spec/twitter/base_spec.rb
require 'helper' describe Twitter::Base do before do @base = Twitter::Base.new('id' => 1) end describe "#[]" do it "should be able to call methods using [] with symbol" do @base[:object_id].should be_an Integer end it "should be able to call methods using [] with string" do @base['object_id'].should be_an Integer end it "should return nil for missing method" do @base[:foo].should be_nil @base['foo'].should be_nil end end describe "#to_hash" do it "should return a hash" do @base.to_hash.should be_a Hash @base.to_hash['id'].should == 1 end end describe "identical objects" do it "should have the same object_id" do @base.object_id.should == Twitter::Base.new('id' => 1).object_id end end end
mislav/twitter
lib/twitter/action.rb
<filename>lib/twitter/action.rb require 'twitter/base' require 'twitter/creatable' module Twitter class Action < Twitter::Base include Twitter::Creatable lazy_attr_reader :max_position, :min_position end end
mislav/twitter
spec/twitter/client_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @keys = Twitter::Config::VALID_OPTIONS_KEYS end context "with module configuration" do before do Twitter.configure do |config| @keys.each do |key| config.send("#{key}=", key) end end end after do Twitter.reset end it "should inherit module configuration" do api = Twitter::Client.new @keys.each do |key| api.send(key).should == key end end context "with class configuration" do before do @configuration = { :consumer_key => 'CK', :consumer_secret => 'CS', :oauth_token => 'OT', :oauth_token_secret => 'OS', :adapter => :typhoeus, :endpoint => 'http://tumblr.com/', :gateway => 'gateway.example.com', :proxy => 'http://erik:sekret@proxy.example.com:8080', :search_endpoint => 'http://google.com/', :media_endpoint => 'https://upload.twitter.com/', :user_agent => 'Custom User Agent', :connection_options => {:timeout => 10}, } end context "during initialization" do it "should override module configuration" do api = Twitter::Client.new(@configuration) @keys.each do |key| api.send(key).should == @configuration[key] end end end context "after initilization" do it "should override module configuration after initialization" do api = Twitter::Client.new @configuration.each do |key, value| api.send("#{key}=", value) end @keys.each do |key| api.send(key).should == @configuration[key] end end end end end it "should not cache the screen name across clients" do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) client1 = Twitter::Client.new client1.current_user.screen_name.should == 'sferik' stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("pengwynn.json"), :headers => {:content_type => "application/json; charset=utf-8"}) client2 = Twitter::Client.new client2.current_user.screen_name.should == 'pengwynn' end it "should recursively merge connection options" do stub_get("/1/statuses/user_timeline.json"). with(:query => {:screen_name => "sferik"}, :headers => {"Accept" => "application/json", "User-Agent" => "Custom User Agent"}). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) client = Twitter::Client.new(:connection_options => {:headers => {:user_agent => 'Custom User Agent'}}) client.user_timeline("sferik") a_get("/1/statuses/user_timeline.json"). with(:query => {:screen_name => "sferik"}, :headers => {"User-Agent" => "Custom User Agent"}). should have_been_made end end
mislav/twitter
lib/twitter/point.rb
<gh_stars>1-10 require 'twitter/base' module Twitter class Point < Twitter::Base lazy_attr_reader :coordinates # @param other [Twitter::Point] # @return [Boolean] def ==(other) super || (other.class == self.class && other.coordinates == self.coordinates) end # @return [Integer] def latitude coordinates[0] end alias :lat :latitude # @return [Integer] def longitude coordinates[1] end alias :long :longitude alias :lng :longitude end end
mislav/twitter
spec/twitter/client/accounts_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#rate_limit_status" do before do stub_get("/1/account/rate_limit_status.json"). to_return(:body => fixture("rate_limit_status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.rate_limit_status a_get("/1/account/rate_limit_status.json"). should have_been_made end it "should return the remaining number of API requests available to the requesting user before the API limit is reached" do rate_limit_status = @client.rate_limit_status rate_limit_status.should be_a Twitter::RateLimitStatus rate_limit_status.remaining_hits.should == 19993 end end describe "#verify_credentials" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.verify_credentials a_get("/1/account/verify_credentials.json"). should have_been_made end it "should return the requesting user" do user = @client.verify_credentials user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#end_session" do before do stub_post("/1/account/end_session.json"). to_return(:body => fixture("end_session.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.end_session a_post("/1/account/end_session.json"). should have_been_made end it "should return a null cookie" do end_session = @client.end_session end_session['error'].should == "Logged out." end end describe "#update_delivery_device" do before do stub_post("/1/account/update_delivery_device.json"). with(:body => {:device => "sms"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_delivery_device("sms") a_post("/1/account/update_delivery_device.json"). with(:body => {:device => "sms"}). should have_been_made end it "should return a user" do user = @client.update_delivery_device("sms") user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#update_profile" do before do stub_post("/1/account/update_profile.json"). with(:body => {:url => "http://github.com/sferik/"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_profile(:url => "http://github.com/sferik/") a_post("/1/account/update_profile.json"). with(:body => {:url => "http://github.com/sferik/"}). should have_been_made end it "should return a user" do user = @client.update_profile(:url => "http://github.com/sferik/") user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#update_profile_background_image" do before do stub_post("/1/account/update_profile_background_image.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_profile_background_image(fixture("we_concept_bg2.png")) a_post("/1/account/update_profile_background_image.json"). should have_been_made end it "should return a user" do user = @client.update_profile_background_image(fixture("we_concept_bg2.png")) user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#update_profile_colors" do before do stub_post("/1/account/update_profile_colors.json"). with(:body => {:profile_background_color => "000000"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_profile_colors(:profile_background_color => "000000") a_post("/1/account/update_profile_colors.json"). with(:body => {:profile_background_color => "000000"}). should have_been_made end it "should return a user" do user = @client.update_profile_colors(:profile_background_color => "000000") user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#update_profile_image" do before do stub_post("/1/account/update_profile_image.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_profile_image(fixture("me.jpeg")) a_post("/1/account/update_profile_image.json"). should have_been_made end it "should return a user" do user = @client.update_profile_image(fixture("me.jpeg")) user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#settings" do before do stub_get("/1/account/settings.json"). to_return(:body => fixture("settings.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_post("/1/account/settings.json"). with(:body => {:trend_location_woeid => "23424803"}). to_return(:body => fixture("settings.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource on GET" do @client.settings a_get("/1/account/settings.json"). should have_been_made end it "should return settings" do settings = @client.settings settings.should be_a Twitter::Settings settings.language.should == 'en' end it "should request the correct resource on POST" do @client.settings(:trend_location_woeid => "23424803") a_post("/1/account/settings.json"). with(:body => {:trend_location_woeid => "23424803"}). should have_been_made end it "should return settings" do settings = @client.settings(:trend_location_woeid => "23424803") settings.should be_a Twitter::Settings settings.language.should == 'en' end end end
mislav/twitter
lib/twitter/entity/hashtag.rb
<filename>lib/twitter/entity/hashtag.rb<gh_stars>1-10 require 'twitter/entity' module Twitter class Entity::Hashtag < Twitter::Entity lazy_attr_reader :text end end
mislav/twitter
lib/twitter/config.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'twitter/version' module Twitter # Defines constants and methods related to configuration module Config # The HTTP connection adapter that will be used to connect if none is set DEFAULT_ADAPTER = :net_http # The Faraday connection options if none is set DEFAULT_CONNECTION_OPTIONS = {} # The consumer key if none is set DEFAULT_CONSUMER_KEY = nil # The consumer secret if none is set DEFAULT_CONSUMER_SECRET = nil # The endpoint that will be used to connect if none is set # # @note This is configurable in case you want to use HTTP instead of HTTPS, specify a different API version, or use a Twitter-compatible endpoint. # @see http://status.net/wiki/Twitter-compatible_API # @see http://en.blog.wordpress.com/2009/12/12/twitter-api/ # @see http://staff.tumblr.com/post/287703110/api # @see http://developer.typepad.com/typepad-twitter-api/twitter-api.html DEFAULT_ENDPOINT = 'https://api.twitter.com' # The gateway server if none is set DEFAULT_GATEWAY = nil # This endpoint will be used by default when updating statuses with media DEFAULT_MEDIA_ENDPOINT = 'https://upload.twitter.com' # The oauth token if none is set DEFAULT_OAUTH_TOKEN = nil # The oauth token secret if none is set DEFAULT_OAUTH_TOKEN_SECRET = nil # The proxy server if none is set DEFAULT_PROXY = nil # The search endpoint that will be used to connect if none is set # # @note This is configurable in case you want to use HTTP instead of HTTPS or use a Twitter-compatible endpoint. # @see http://status.net/wiki/Twitter-compatible_API DEFAULT_SEARCH_ENDPOINT = 'https://search.twitter.com' # The value sent in the 'User-Agent' header if none is set DEFAULT_USER_AGENT = "Twitter Ruby Gem #{Twitter::Version}" # An array of valid keys in the options hash when configuring a {Twitter::Client} VALID_OPTIONS_KEYS = [ :adapter, :connection_options, :consumer_key, :consumer_secret, :endpoint, :gateway, :oauth_token, :oauth_token_secret, :proxy, :search_endpoint, :user_agent, :media_endpoint ] attr_accessor *VALID_OPTIONS_KEYS # When this module is extended, set all configuration options to their default values def self.extended(base) base.reset end # Convenience method to allow configuration options to be set in a block def configure yield self self end # Create a hash of options and their values def options options = {} VALID_OPTIONS_KEYS.each{|k| options[k] = send(k)} options end # Reset all configuration options to defaults def reset self.adapter = DEFAULT_ADAPTER self.connection_options = DEFAULT_CONNECTION_OPTIONS self.consumer_key = DEFAULT_CONSUMER_KEY self.consumer_secret = DEFAULT_CONSUMER_SECRET self.endpoint = DEFAULT_ENDPOINT self.gateway = DEFAULT_GATEWAY self.media_endpoint = DEFAULT_MEDIA_ENDPOINT self.oauth_token = DEFAULT_OAUTH_TOKEN self.oauth_token_secret = DEFAULT_OAUTH_TOKEN_SECRET self.proxy = DEFAULT_PROXY self.search_endpoint = DEFAULT_SEARCH_ENDPOINT self.user_agent = DEFAULT_USER_AGENT self end end end
mislav/twitter
lib/twitter/language.rb
require 'twitter/base' module Twitter class Language < Twitter::Base lazy_attr_reader :code, :name, :status end end
mislav/twitter
lib/twitter/client.rb
require 'twitter/action_factory' require 'twitter/authenticatable' require 'twitter/config' require 'twitter/configuration' require 'twitter/connection' require 'twitter/core_ext/enumerable' require 'twitter/core_ext/hash' require 'twitter/cursor' require 'twitter/direct_message' require 'twitter/error/forbidden' require 'twitter/error/not_found' require 'twitter/favorite' require 'twitter/follow' require 'twitter/language' require 'twitter/list' require 'twitter/mention' require 'twitter/metadata' require 'twitter/oembed' require 'twitter/photo' require 'twitter/place' require 'twitter/point' require 'twitter/polygon' require 'twitter/rate_limit_status' require 'twitter/relationship' require 'twitter/reply' require 'twitter/request' require 'twitter/retweet' require 'twitter/saved_search' require 'twitter/search_results' require 'twitter/settings' require 'twitter/size' require 'twitter/status' require 'twitter/suggestion' require 'twitter/trend' require 'twitter/user' module Twitter # Wrapper for the Twitter REST API # # @note All methods have been separated into modules and follow the same grouping used in {http://dev.twitter.com/doc the Twitter API Documentation}. # @see http://dev.twitter.com/pages/every_developer class Client include Twitter::Authenticatable include Twitter::Connection include Twitter::Request attr_accessor *Config::VALID_OPTIONS_KEYS MAX_USERS_PER_REQUEST = 100 # Initializes a new API object # # @param attrs [Hash] # @return [Twitter::Client] def initialize(attrs={}) attrs = Twitter.options.merge(attrs) Config::VALID_OPTIONS_KEYS.each do |key| instance_variable_set("@#{key}".to_sym, attrs[key]) end end # Returns the configured screen name or the screen name of the authenticated user # # @return [Twitter::User] def current_user @current_user ||= Twitter::User.new(self.verify_credentials.attrs) end # Returns the remaining number of API requests available to the requesting user # # @see https://dev.twitter.com/docs/api/1/get/account/rate_limit_status # @rate_limited No # @requires_authentication No # # This will return the requesting IP's rate limit status. If you want the authenticating user's rate limit status you must authenticate. # @param options [Hash] A customizable set of options. # @return [Twitter::RateLimitStatus] # @example Return the remaining number of API requests available to the requesting user # Twitter.rate_limit_status def rate_limit_status(options={}) rate_limit_status = get("/1/account/rate_limit_status.json", options) Twitter::RateLimitStatus.new(rate_limit_status) end # Returns the requesting user if authentication was successful, otherwise raises {Twitter::Error::Unauthorized} # # @see https://dev.twitter.com/docs/api/1/get/account/verify_credentials # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the requesting user if authentication was successful # Twitter.verify_credentials def verify_credentials(options={}) user = get("/1/account/verify_credentials.json", options) Twitter::User.new(user) end # Ends the session of the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/account/end_session # @rate_limited No # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @return [Hash] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example End the session of the authenticating user # Twitter.end_session def end_session(options={}) post("/1/account/end_session.json", options) end # Sets which device Twitter delivers updates to for the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/account/update_delivery_device # @rate_limited No # @requires_authentication Yes # @param device [String] Must be one of: 'sms', 'none'. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Turn SMS updates on for the authenticating user # Twitter.update_delivery_device('sms') def update_delivery_device(device, options={}) user = post("/1/account/update_delivery_device.json", options.merge(:device => device)) Twitter::User.new(user) end # Sets values that users are able to set under the "Account" tab of their settings page # # @see https://dev.twitter.com/docs/api/1/post/account/update_profile # @note Only the options specified will be updated. # @rate_limited No # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [String] :name Full name associated with the profile. Maximum of 20 characters. # @option options [String] :url URL associated with the profile. Will be prepended with "http://" if not present. Maximum of 100 characters. # @option options [String] :location The city or country describing where the user of the account is located. The contents are not normalized or geocoded in any way. Maximum of 30 characters. # @option options [String] :description A description of the user owning the account. Maximum of 160 characters. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Set authenticating user's name to <NAME> # Twitter.update_profile(:name => "<NAME>") def update_profile(options={}) user = post("/1/account/update_profile.json", options) Twitter::User.new(user) end # Updates the authenticating user's profile background image # # @see https://dev.twitter.com/docs/api/1/post/account/update_profile_background_image # @rate_limited No # @requires_authentication Yes # @param image [String] The background image for the profile. Must be a valid GIF, JPG, or PNG image of less than 800 kilobytes in size. Images with width larger than 2048 pixels will be scaled down. # @param options [Hash] A customizable set of options. # @option options [Boolean] :tile Whether or not to tile the background image. If set to true the background image will be displayed tiled. The image will not be tiled otherwise. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Update the authenticating user's profile background image # Twitter.update_profile_background_image(File.new("we_concept_bg2.png")) def update_profile_background_image(image, options={}) user = post("/1/account/update_profile_background_image.json", options.merge(:image => image)) Twitter::User.new(user) end # Sets one or more hex values that control the color scheme of the authenticating user's profile # # @see https://dev.twitter.com/docs/api/1/post/account/update_profile_colors # @rate_limited No # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [String] :profile_background_color Profile background color. # @option options [String] :profile_text_color Profile text color. # @option options [String] :profile_link_color Profile link color. # @option options [String] :profile_sidebar_fill_color Profile sidebar's background color. # @option options [String] :profile_sidebar_border_color Profile sidebar's border color. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Set authenticating user's profile background to black # Twitter.update_profile_colors(:profile_background_color => '000000') def update_profile_colors(options={}) user = post("/1/account/update_profile_colors.json", options) Twitter::User.new(user) end # Updates the authenticating user's profile image # # @see https://dev.twitter.com/docs/api/1/post/account/update_profile_image # @note This method asynchronously processes the uploaded file before updating the user's profile image URL. You can either update your local cache the next time you request the user's information, or, at least 5 seconds after uploading the image, ask for the updated URL using {Twitter::Client::User#profile_image}. # @rate_limited No # @requires_authentication Yes # @param image [String] The avatar image for the profile. Must be a valid GIF, JPG, or PNG image of less than 700 kilobytes in size. Images with width larger than 500 pixels will be scaled down. Animated GIFs will be converted to a static GIF of the first frame, removing the animation. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The authenticated user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Update the authenticating user's profile image # Twitter.update_profile_image(File.new("me.jpeg")) def update_profile_image(image, options={}) user = post("/1/account/update_profile_image.json", options.merge(:image => image)) Twitter::User.new(user) end # Updates the authenticating user's settings. # Or, if no options supplied, returns settings (including current trend, geo and sleep time information) for the authenticating user. # # @see https://dev.twitter.com/docs/api/1/post/account/settings # @see https://dev.twitter.com/docs/api/1/get/account/settings # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :trend_location_woeid The Yahoo! Where On Earth ID to use as the user's default trend location. Global information is available by using 1 as the WOEID. The woeid must be one of the locations returned by {https://dev.twitter.com/docs/api/1/get/trends/available GET trends/available}. # @option options [Boolean, String, Integer] :sleep_time_enabled When set to true, 't' or 1, will enable sleep time for the user. Sleep time is the time when push or SMS notifications should not be sent to the user. # @option options [Integer] :start_sleep_time The hour that sleep time should begin if it is enabled. The value for this parameter should be provided in {http://en.wikipedia.org/wiki/ISO_8601 ISO8601} format (i.e. 00-23). The time is considered to be in the same timezone as the user's time_zone setting. # @option options [Integer] :end_sleep_time The hour that sleep time should end if it is enabled. The value for this parameter should be provided in {http://en.wikipedia.org/wiki/ISO_8601 ISO8601} format (i.e. 00-23). The time is considered to be in the same timezone as the user's time_zone setting. # @option options [String] :time_zone The timezone dates and times should be displayed in for the user. The timezone must be one of the {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Rails TimeZone} names. # @option options [String] :lang The language which Twitter should render in for this user. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by {https://dev.twitter.com/docs/api/1/get/help/languages GET help/languages}. # @return [Twitter::Settings] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the settings for the authenticating user. # Twitter.settings def settings(options={}) settings = if options.size.zero? get("/1/account/settings.json", options) else post("/1/account/settings.json", options) end Twitter::Settings.new(settings) end # Returns activity about me # # @note Undocumented # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @return [Array] An array of actions # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return activity about me # Twitter.activity_about_me def activity_about_me(options={}) get("/i/activity/about_me.json", options).map do |action| Twitter::ActionFactory.new(action) end end # Returns activity by friends # # @note Undocumented # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @return [Array] An array of actions # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid./ # @example Return activity by friends # Twitter.activity_by_friends def activity_by_friends(options={}) get("/i/activity/by_friends.json", options).map do |action| Twitter::ActionFactory.new(action) end end # Returns an array of user objects that the authenticating user is blocking # # @see https://dev.twitter.com/docs/api/1/get/blocks/blocking # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :page Specifies the page of results to retrieve. # @return [Array<Twitter::User>] User objects that the authenticating user is blocking. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return an array of user objects that the authenticating user is blocking # Twitter.blocking def blocking(options={}) get("/1/blocks/blocking.json", options).map do |user| Twitter::User.new(user) end end # Returns an array of numeric user ids the authenticating user is blocking # # @see https://dev.twitter.com/docs/api/1/get/blocks/blocking/ids # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @return [Array] Numeric user ids the authenticating user is blocking. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return an array of numeric user ids the authenticating user is blocking # Twitter.blocking_ids def blocked_ids(options={}) get("/1/blocks/blocking/ids.json", options) end # Returns true if the authenticating user is blocking a target user # # @see https://dev.twitter.com/docs/api/1/get/blocks/exists # @requires_authentication Yes # @rate_limited Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Boolean] true if the authenticating user is blocking the target user, otherwise false. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Check whether the authenticating user is blocking @sferik # Twitter.block?('sferik') # Twitter.block?(7505382) # Same as above def block?(user, options={}) options.merge_user!(user) get("/1/blocks/exists.json", options, :raw => true) true rescue Twitter::Error::NotFound false end # Blocks the user specified by the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/blocks/create # @note Destroys a friendship to the blocked user if it exists. # @rate_limited Yes # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The blocked user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Block and unfriend @sferik as the authenticating user # Twitter.block('sferik') # Twitter.block(7505382) # Same as above def block(user, options={}) options.merge_user!(user) user = post("/1/blocks/create.json", options) Twitter::User.new(user) end # Un-blocks the user specified by the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/blocks/destroy # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The un-blocked user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Un-block @sferik as the authenticating user # Twitter.unblock('sferik') # Twitter.unblock(7505382) # Same as above def unblock(user, options={}) options.merge_user!(user) user = delete("/1/blocks/destroy.json", options) Twitter::User.new(user) end # Returns the 20 most recent direct messages sent to the authenticating user # # @see https://dev.twitter.com/docs/api/1/get/direct_messages # @note This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Integer] :page Specifies the page of results to retrieve. # @return [Array<Twitter::DirectMessage>] Direct messages sent to the authenticating user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent direct messages sent to the authenticating user # Twitter.direct_messages def direct_messages(options={}) get("/1/direct_messages.json", options).map do |direct_message| Twitter::DirectMessage.new(direct_message) end end # Returns the 20 most recent direct messages sent by the authenticating user # # @see https://dev.twitter.com/docs/api/1/get/direct_messages/sent # @note This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Integer] :page Specifies the page of results to retrieve. # @return [Array<Twitter::DirectMessage>] Direct messages sent by the authenticating user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent direct messages sent by the authenticating user # Twitter.direct_messages_sent def direct_messages_sent(options={}) get("/1/direct_messages/sent.json", options).map do |direct_message| Twitter::DirectMessage.new(direct_message) end end # Destroys a direct message # # @see https://dev.twitter.com/docs/api/1/post/direct_messages/destroy/:id # @note This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. # @rate_limited No # @requires_authentication Yes # @param id [Integer] The ID of the direct message to delete. # @param options [Hash] A customizable set of options. # @return [Twitter::DirectMessage] The deleted message. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Destroys the direct message with the ID 1825785544 # Twitter.direct_message_destroy(1825785544) def direct_message_destroy(id, options={}) direct_message = delete("/1/direct_messages/destroy/#{id}.json", options) Twitter::DirectMessage.new(direct_message) end # Sends a new direct message to the specified user from the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/direct_messages/new # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param text [String] The text of your direct message, up to 140 characters. # @param options [Hash] A customizable set of options. # @return [Twitter::DirectMessage] The sent message. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Send a direct message to @sferik from the authenticating user # Twitter.direct_message_create('sferik', "I'm sending you this message via @gem!") # Twitter.direct_message_create(7505382, "I'm sending you this message via @gem!") # Same as above def direct_message_create(user, text, options={}) options.merge_user!(user) direct_message = post("/1/direct_messages/new.json", options.merge(:text => text)) Twitter::DirectMessage.new(direct_message) end alias :d :direct_message_create # Returns a single direct message, specified by id. # # @see https://dev.twitter.com/docs/api/1/get/direct_messages/show/%3Aid # @note This method requires an access token with RWD (read, write & direct message) permissions. Consult The Application Permission Model for more information. # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The ID of the direct message to retrieve. # @param options [Hash] A customizable set of options. # @return [Twitter::DirectMessage] The requested message. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the direct message with the id 1825786345 # Twitter.direct_message(1825786345) def direct_message(id, options={}) direct_message = get("/1/direct_messages/show/#{id}.json", options) Twitter::DirectMessage.new(direct_message) end # @see https://dev.twitter.com/docs/api/1/get/favorites # @rate_limited Yes # @requires_authentication No # @overload favorites(options={}) # Returns the 20 most recent favorite statuses for the authenticating user # # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @return [Array<Twitter::Status>] favorite statuses. # @example Return the 20 most recent favorite statuses for the authenticating user # Twitter.favorites # @overload favorites(user, options={}) # Returns the 20 most recent favorite statuses for the specified user # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @return [Array<Twitter::Status>] favorite statuses. # @example Return the 20 most recent favorite statuses for @sferik # Twitter.favorites('sferik') def favorites(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop get("/1/favorites/#{user}.json", options) else get("/1/favorites.json", options) end.map do |status| Twitter::Status.new(status) end end # Favorites the specified status as the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/favorites/create/:id # @rate_limited No # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @return [Twitter::Status] The favorited status. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Favorite the status with the ID 25938088801 # Twitter.favorite(25938088801) def favorite(id, options={}) status = post("/1/favorites/create/#{id}.json", options) Twitter::Status.new(status) end alias :favorite_create :favorite # Un-favorites the specified status as the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/favorites/destroy/:id # @rate_limited No # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @return [Twitter::Status] The un-favorited status. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Un-favorite the status with the ID 25938088801 # Twitter.unfavorite(25938088801) def unfavorite(id, options={}) status = delete("/1/favorites/destroy/#{id}.json", options) Twitter::Status.new(status) end alias :favorite_destroy :unfavorite # @see https://dev.twitter.com/docs/api/1/get/followers/ids # @rate_limited Yes # @requires_authentication No unless requesting it from a protected user # # If getting this data of a protected user, you must authenticate (and be allowed to see that user). # @overload follower_ids(options={}) # Returns an array of numeric IDs for every user following the authenticated user # # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return the authenticated user's followers' IDs # Twitter.follower_ids # @overload follower_ids(user, options={}) # Returns an array of numeric IDs for every user following the specified user # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. This is recommended for users who are following many users. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return @sferik's followers' IDs # Twitter.follower_ids('sferik') # Twitter.follower_ids(7505382) # Same as above def follower_ids(*args) options = {:cursor => -1} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop options.merge_user!(user) cursor = get("/1/followers/ids.json", options) Twitter::Cursor.new(cursor, 'ids') end # @see https://dev.twitter.com/docs/api/1/get/friends/ids # @rate_limited Yes # @requires_authentication No unless requesting it from a protected user # # If getting this data of a protected user, you must authenticate (and be allowed to see that user). # @overload friend_ids(options={}) # Returns an array of numeric IDs for every user the authenticated user is following # # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. This is recommended for users who are following many users. Provide a value of -1 to begin paging. Provide values as returned in the response body's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return the authenticated user's friends' IDs # Twitter.friend_ids # @overload friend_ids(user, options={}) # Returns an array of numeric IDs for every user the specified user is following # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return @sferik's friends' IDs # Twitter.friend_ids('sferik') # Twitter.friend_ids(7505382) # Same as above def friend_ids(*args) options = {:cursor => -1} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop options.merge_user!(user) cursor = get("/1/friends/ids.json", options) Twitter::Cursor.new(cursor, 'ids') end # Test for the existence of friendship between two users # # @see https://dev.twitter.com/docs/api/1/get/friendships/exists # @note Consider using {Twitter::Client::FriendsAndFollowers#friendship} instead of this method. # @rate_limited Yes # @requires_authentication No unless user_a or user_b is protected # @param user_a [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the subject user. # @param user_b [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the user to test for following. # @param options [Hash] A customizable set of options. # @return [Boolean] true if user_a follows user_b, otherwise false. # @example Return true if @sferik follows @pengwynn # Twitter.friendship?('sferik', 'pengwynn') # Twitter.friendship?('sferik', 14100886) # Same as above # Twitter.friendship?(7505382, 14100886) # Same as above def friendship?(user_a, user_b, options={}) options.merge_user!(user_a, nil, "a") options.merge_user!(user_b, nil, "b") get("/1/friendships/exists.json", options) end # Returns an array of numeric IDs for every user who has a pending request to follow the authenticating user # # @see https://dev.twitter.com/docs/api/1/get/friendships/incoming # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return an array of numeric IDs for every user who has a pending request to follow the authenticating user # Twitter.friendships_incoming def friendships_incoming(options={}) options = {:cursor => -1}.merge(options) cursor = get("/1/friendships/incoming.json", options) Twitter::Cursor.new(cursor, 'ids') end # Returns an array of numeric IDs for every protected user for whom the authenticating user has a pending follow request # # @see https://dev.twitter.com/docs/api/1/get/friendships/outgoing # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return an array of numeric IDs for every protected user for whom the authenticating user has a pending follow request # Twitter.friendships_outgoing def friendships_outgoing(options={}) options = {:cursor => -1}.merge(options) cursor = get("/1/friendships/outgoing.json", options) Twitter::Cursor.new(cursor, 'ids') end # Returns detailed information about the relationship between two users # # @see https://dev.twitter.com/docs/api/1/get/friendships/show # @rate_limited Yes # @requires_authentication No # @param source [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the source user. # @param target [Integer, String, Twitter::User] The Twitter user ID, screen name, or object of the target user. # @param options [Hash] A customizable set of options. # @return [Twitter::Relationship] # @example Return the relationship between @sferik and @pengwynn # Twitter.friendship('sferik', 'pengwynn') # Twitter.friendship('sferik', 14100886) # Same as above # Twitter.friendship(7505382, 14100886) # Same as above def friendship(source, target, options={}) options.merge_user!(source, "source") options[:source_id] = options.delete(:source_user_id) unless options[:source_user_id].nil? options.merge_user!(target, "target") options[:target_id] = options.delete(:target_user_id) unless options[:target_user_id].nil? relationship = get("/1/friendships/show.json", options)['relationship'] Twitter::Relationship.new(relationship) end alias :friendship_show :friendship alias :relationship :friendship # Allows the authenticating user to follow the specified users, unless they are already followed # # @see https://dev.twitter.com/docs/api/1/post/friendships/create # @rate_limited No # @requires_authentication Yes # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean] :follow (false) Enable notifications for the target user. # @return [Twitter::User] The followed user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Follow @sferik # Twitter.follow('sferik') def follow(*args) options = args.last.is_a?(Hash) ? args.pop : {} # Twitter always turns on notifications if the "follow" option is present, even if it's set to false # so only send follow if it's true options.merge!(:follow => true) if options.delete(:follow) friend_ids = self.friend_ids.ids user_ids = self.users(args).map(&:id) (user_ids - friend_ids).threaded_map do |user| begin user = post("/1/friendships/create.json", options.merge_user(user)) Twitter::User.new(user) rescue Twitter::Error::Forbidden # This error will be raised if the user doesn't have permission to # follow list_member, for whatever reason. end end.compact end alias :friendship_create :follow # Allows the authenticating user to follow the specified users # # @see https://dev.twitter.com/docs/api/1/post/friendships/create # @rate_limited No # @requires_authentication Yes # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @option options [Boolean] :follow (false) Enable notifications for the target user. # @return [Array<Twitter::User>] The followed users. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Follow @sferik # Twitter.follow!('sferik') def follow!(*args) options = args.last.is_a?(Hash) ? args.pop : {} # Twitter always turns on notifications if the "follow" option is present, even if it's set to false # so only send follow if it's true options.merge!(:follow => true) if options.delete(:follow) args.threaded_map do |user| begin user = post("/1/friendships/create.json", options.merge_user(user)) Twitter::User.new(user) rescue Twitter::Error::Forbidden # This error will be raised if the user doesn't have permission to # follow list_member, for whatever reason. end end.compact end alias :friendship_create! :follow! # Allows the authenticating user to unfollow the specified users # # @see https://dev.twitter.com/docs/api/1/post/friendships/destroy # @rate_limited No # @requires_authentication Yes # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Array<Twitter::User>] The unfollowed users. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Unfollow @sferik # Twitter.unfollow('sferik') def unfollow(*args) options = args.last.is_a?(Hash) ? args.pop : {} args.threaded_map do |user| user = delete("/1/friendships/destroy.json", options.merge_user(user)) Twitter::User.new(user) end end alias :friendship_destroy :unfollow # Returns the relationship of the authenticating user to the comma separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none. # # @see https://dev.twitter.com/docs/api/1/get/friendships/lookup # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @return [Twitter::Relationship] # @overload friendships(*users, options={}) # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Array<Twitter::User>] The requested users. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return extended information for @sferik and @pengwynn # Twitter.friendships('sferik', 'pengwynn') # Twitter.friendships('sferik', 14100886) # Same as above # Twitter.friendships(7505382, 14100886) # Same as above def friendships(*args) options = args.last.is_a?(Hash) ? args.pop : {} users = args options.merge_users!(Array(users)) get("/1/friendships/lookup.json", options).map do |user| Twitter::User.new(user) end end # Allows one to enable or disable retweets and device notifications from the specified user. # # @see https://dev.twitter.com/docs/api/1/post/friendships/update # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean] :device Enable/disable device notifications from the target user. # @option options [Boolean] :retweets Enable/disable retweets from the target user. # @return [Twitter::Relationship] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Enable rewteets and devise notifications for @sferik # Twitter.friendship_update('sferik', :device => true, :retweets => true) def friendship_update(user, options={}) options.merge_user!(user) relationship = post("/1/friendships/update.json", options)['relationship'] Twitter::Relationship.new(relationship) end # Returns an array of user_ids that the currently authenticated user does not want to see retweets from. # # @see https://dev.twitter.com/docs/api/1/get/friendships/no_retweet_ids # @rate_limited Yes # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean] :stringify_ids Many programming environments will not consume our ids due to their size. Provide this option to have ids returned as strings instead. Read more about Twitter IDs, JSON and Snowflake. # @return [Array<Integer>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Enable rewteets and devise notifications for @sferik # Twitter.no_retweet_ids def no_retweet_ids(options={}) get("/1/friendships/no_retweet_ids.json", options) end # Allows the authenticating user to accept the specified user's follow request # # @note Undocumented # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The accepted user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Accept @sferik's follow request # Twitter.accept('sferik') def accept(user, options={}) options.merge_user!(user) user = post("/1/friendships/accept.json", options) Twitter::User.new(user) end # Allows the authenticating user to deny the specified user's follow request # # @note Undocumented # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The denied user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Deny @sferik's follow request # Twitter.deny('sferik') def deny(user, options={}) options.merge_user!(user) user = post("/1/friendships/deny.json", options) Twitter::User.new(user) end # Returns the current configuration used by Twitter # # @see https://dev.twitter.com/docs/api/1/get/help/configuration # @rate_limited Yes # @requires_authentication No # @return [Twitter::Configuration] Twitter's configuration. # @example Return the current configuration used by Twitter # Twitter.configuration def configuration(options={}) configuration = get("/1/help/configuration.json", options) Twitter::Configuration.new(configuration) end # Returns the list of languages supported by Twitter # # @see https://dev.twitter.com/docs/api/1/get/help/languages # @rate_limited Yes # @requires_authentication No # @return [Array<Twitter::Language>] # @example Return the list of languages Twitter supports # Twitter.languages def languages(options={}) get("/1/help/languages.json", options).map do |language| Twitter::Language.new(language) end end # Returns {https://twitter.com/privacy Twitter's Privacy Policy} # # @see https://dev.twitter.com/docs/api/1/get/legal/privacy # @rate_limited Yes # @requires_authentication No # @return [String] # @example Return {https://twitter.com/privacy Twitter's Privacy Policy} # Twitter.privacy def privacy(options={}) get("/1/legal/privacy.json", options)['privacy'] end # Returns {https://twitter.com/tos Twitter's Terms of Service} # # @see https://dev.twitter.com/docs/api/1/get/legal/tos # @rate_limited Yes # @requires_authentication No # @return [String] # @example Return {https://twitter.com/tos Twitter's Terms of Service} # Twitter.tos def tos(options={}) get("/1/legal/tos.json", options)['tos'] end # Returns all lists the authenticating or specified user subscribes to, including their own # # @see https://dev.twitter.com/docs/api/1/get/lists/all # @rate_limited Yes # @requires_authentication Supported # @overload lists_subscribed_to(options={}) # @param options [Hash] A customizable set of options. # @return [Array<Twitter::Status>] # @example Return all lists the authenticating user subscribes to # Twitter.lists_subscribed_to # @overload lists_subscribed_to(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Array<Twitter::List>] # @example Return all lists the specified user subscribes to # Twitter.lists_subscribed_to('sferik') # Twitter.lists_subscribed_to(8863586) def lists_subscribed_to(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) end get("/1/lists/all.json", options).map do |list| Twitter::List.new(list) end end # Show tweet timeline for members of the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/statuses # @rate_limited Yes # @requires_authentication No # @overload list_timeline(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :per_page The number of results to retrieve. # @return [Array<Twitter::Status>] # @example Show tweet timeline for members of the authenticated user's "presidents" list # Twitter.list_timeline('presidents') # Twitter.list_timeline(8863586) # @overload list_timeline(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :per_page The number of results to retrieve. # @return [Array<Twitter::Status>] # @example Show tweet timeline for members of @sferik's "presidents" list # Twitter.list_timeline('sferik', 'presidents') # Twitter.list_timeline('sferik', 8863586) # Twitter.list_timeline(7505382, 'presidents') # Twitter.list_timeline(7505382, 8863586) def list_timeline(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end get("/1/lists/statuses.json", options).map do |status| Twitter::Status.new(status) end end # Removes the specified member from the list # # @see https://dev.twitter.com/docs/api/1/post/lists/members/destroy # @rate_limited No # @requires_authentication Yes # @overload list_remove_member(list, user_to_remove, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_remove [Integer, String] The user id or screen name of the list member to remove. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Remove @BarackObama from the authenticated user's "presidents" list # Twitter.list_remove_member('presidents', 813286) # Twitter.list_remove_member('presidents', 'BarackObama') # Twitter.list_remove_member(8863586, 'BarackObama') # @overload list_remove_member(user, list, user_to_remove, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_remove [Integer, String] The user id or screen name of the list member to remove. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Remove @BarackObama from @sferik's "presidents" list # Twitter.list_remove_member('sferik', 'presidents', 813286) # Twitter.list_remove_member('sferik', 'presidents', 'BarackObama') # Twitter.list_remove_member('sferik', 8863586, 'BarackObama') # Twitter.list_remove_member(7505382, 'presidents', 813286) def list_remove_member(*args) options = args.last.is_a?(Hash) ? args.pop : {} user_to_remove = args.pop options.merge_user!(user_to_remove) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/members/destroy.json", options) Twitter::List.new(list) end # List the lists the specified user has been added to # # @see https://dev.twitter.com/docs/api/1/get/lists/memberships # @rate_limited Yes # @requires_authentication Supported # @overload memberships(options={}) # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List the lists the authenticated user has been added to # Twitter.memberships # @overload memberships(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List the lists that @sferik has been added to # Twitter.memberships('sferik') # Twitter.memberships(7505382) def memberships(*args) options = {:cursor => -1}.merge(args.last.is_a?(Hash) ? args.pop : {}) if user = args.pop options.merge_user!(user) end cursor = get("/1/lists/memberships.json", options) Twitter::Cursor.new(cursor, 'lists', Twitter::List) end # Returns the subscribers of the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/subscribers # @rate_limited Yes # @requires_authentication Supported # @overload list_subscribers(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] The subscribers of the specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the subscribers of the authenticated user's "presidents" list # Twitter.list_subscribers('presidents') # Twitter.list_subscribers(8863586) # @overload list_subscribers(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] The subscribers of the specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the subscribers of @sferik's "presidents" list # Twitter.list_subscribers('sferik', 'presidents') # Twitter.list_subscribers('sferik', 8863586) # Twitter.list_subscribers(7505382, 'presidents') def list_subscribers(*args) options = {:cursor => -1}.merge(args.last.is_a?(Hash) ? args.pop : {}) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end cursor = get("/1/lists/subscribers.json", options) Twitter::Cursor.new(cursor, 'users', Twitter::User) end # List the lists the specified user follows # # @see https://dev.twitter.com/docs/api/1/get/lists/subscriptions # @rate_limited Yes # @requires_authentication Supported # @overload subscriptions(options={}) # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List the lists the authenticated user follows # Twitter.subscriptions # @overload subscriptions(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List the lists that @sferik follows # Twitter.subscriptions('sferik') # Twitter.subscriptions(7505382) def subscriptions(*args) options = {:cursor => -1}.merge(args.last.is_a?(Hash) ? args.pop : {}) if user = args.pop options.merge_user!(user) end cursor = get("/1/lists/subscriptions.json", options) Twitter::Cursor.new(cursor, 'lists', Twitter::List) end # Make the authenticated user follow the specified list # # @see https://dev.twitter.com/docs/api/1/post/lists/subscribers/create # @rate_limited No # @requires_authentication Yes # @overload list_subscribe(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Subscribe to the authenticated user's "presidents" list # Twitter.list_subscribe('presidents') # Twitter.list_subscribe(8863586) # @overload list_subscribe(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Subscribe to @sferik's "presidents" list # Twitter.list_subscribe('sferik', 'presidents') # Twitter.list_subscribe('sferik', 8863586) # Twitter.list_subscribe(7505382, 'presidents') def list_subscribe(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/subscribers/create.json", options) Twitter::List.new(list) end # Check if a user is a subscriber of the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/subscribers/show # @rate_limited Yes # @requires_authentication Yes # @overload list_subscriber?(list, user_to_check, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_check [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Boolean] true if user is a subscriber of the specified list, otherwise false. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Check if @BarackObama is a subscriber of the authenticated user's "presidents" list # Twitter.list_subscriber?('presidents', 813286) # Twitter.list_subscriber?(8863586, 813286) # Twitter.list_subscriber?('presidents', 'BarackObama') # @overload list_subscriber?(user, list, user_to_check, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_check [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Boolean] true if user is a subscriber of the specified list, otherwise false. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Check if @BarackObama is a subscriber of @sferik's "presidents" list # Twitter.list_subscriber?('sferik', 'presidents', 813286) # Twitter.list_subscriber?('sferik', 8863586, 813286) # Twitter.list_subscriber?(7505382, 'presidents', 813286) # Twitter.list_subscriber?('sferik', 'presidents', 'BarackObama') # @return [Boolean] true if user is a subscriber of the specified list, otherwise false. def list_subscriber?(*args) options = args.last.is_a?(Hash) ? args.pop : {} user_to_check = args.pop options.merge_user!(user_to_check) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end get("/1/lists/subscribers/show.json", options, :raw => true) true rescue Twitter::Error::NotFound, Twitter::Error::Forbidden false end # Unsubscribes the authenticated user form the specified list # # @see https://dev.twitter.com/docs/api/1/post/lists/subscribers/destroy # @rate_limited No # @requires_authentication Yes # @overload list_unsubscribe(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Unsubscribe from the authenticated user's "presidents" list # Twitter.list_unsubscribe('presidents') # Twitter.list_unsubscribe(8863586) # @overload list_unsubscribe(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Unsubscribe from @sferik's "presidents" list # Twitter.list_unsubscribe('sferik', 'presidents') # Twitter.list_unsubscribe('sferik', 8863586) # Twitter.list_unsubscribe(7505382, 'presidents') def list_unsubscribe(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/subscribers/destroy.json", options) Twitter::List.new(list) end # Adds specified members to a list # # @see https://dev.twitter.com/docs/api/1/post/lists/members/create_all # @note Lists are limited to having 500 members, and you are limited to adding up to 100 members to a list at a time with this method. # @rate_limited No # @requires_authentication Yes # @overload list_add_members(list, users, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Add @BarackObama and @pengwynn to the authenticated user's "presidents" list # Twitter.list_add_members('presidents', ['BarackObama', 'pengwynn']) # Twitter.list_add_members('presidents', [813286, 18755393]) # Twitter.list_add_members(8863586, ['BarackObama', 'pengwynn']) # Twitter.list_add_members(8863586, [813286, 18755393]) # @overload list_add_members(user, list, users, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Add @BarackObama and @pengwynn to @sferik's "presidents" list # Twitter.list_add_members('sferik', 'presidents', ['BarackObama', 'pengwynn']) # Twitter.list_add_members('sferik', 'presidents', [813286, 18755393]) # Twitter.list_add_members(7505382, 'presidents', ['BarackObama', 'pengwynn']) # Twitter.list_add_members(7505382, 'presidents', [813286, 18755393]) # Twitter.list_add_members(7505382, 8863586, ['BarackObama', 'pengwynn']) # Twitter.list_add_members(7505382, 8863586, [813286, 18755393]) def list_add_members(*args) options = args.last.is_a?(Hash) ? args.pop : {} users = args.pop options.merge_users!(Array(users)) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/members/create_all.json", options) Twitter::List.new(list) end # Removes specified members from the list # # @see https://dev.twitter.com/docs/api/1/post/lists/members/destroy_all # @rate_limited No # @requires_authentication Yes # @overload list_remove_members(list, users, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Remove @BarackObama and @pengwynn from the authenticated user's "presidents" list # Twitter.list_remove_members('presidents', ['BarackObama', 'pengwynn']) # Twitter.list_remove_members('presidents', [813286, 18755393]) # Twitter.list_remove_members(8863586, ['BarackObama', 'pengwynn']) # Twitter.list_remove_members(8863586, [813286, 18755393]) # @overload list_remove_members(user, list, users, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Remove @BarackObama and @pengwynn from @sferik's "presidents" list # Twitter.list_remove_members('sferik', 'presidents', ['BarackObama', 'pengwynn']) # Twitter.list_remove_members('sferik', 'presidents', [813286, 18755393]) # Twitter.list_remove_members(7505382, 'presidents', ['BarackObama', 'pengwynn']) # Twitter.list_remove_members(7505382, 'presidents', [813286, 18755393]) # Twitter.list_remove_members(7505382, 8863586, ['BarackObama', 'pengwynn']) # Twitter.list_remove_members(7505382, 8863586, [813286, 18755393]) def list_remove_members(*args) options = args.last.is_a?(Hash) ? args.pop : {} users = args.pop options.merge_users!(Array(users)) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/members/destroy_all.json", options) Twitter::List.new(list) end # Check if a user is a member of the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/members/show # @requires_authentication Yes # @rate_limited Yes # @overload list_member?(list, user_to_check, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_check [Integer, String] The user ID or screen name of the list member. # @param options [Hash] A customizable set of options. # @return [Boolean] true if user is a member of the specified list, otherwise false. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Check if @BarackObama is a member of the authenticated user's "presidents" list # Twitter.list_member?('presidents', 813286) # Twitter.list_member?(8863586, 'BarackObama') # @overload list_member?(user, list, user_to_check, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_check [Integer, String] The user ID or screen name of the list member. # @param options [Hash] A customizable set of options. # @return [Boolean] true if user is a member of the specified list, otherwise false. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Check if @BarackObama is a member of @sferik's "presidents" list # Twitter.list_member?('sferik', 'presidents', 813286) # Twitter.list_member?('sferik', 8863586, 'BarackObama') # Twitter.list_member?(7505382, 'presidents', 813286) def list_member?(*args) options = args.last.is_a?(Hash) ? args.pop : {} user_to_check = args.pop options.merge_user!(user_to_check) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end get("/1/lists/members/show.json", options, :raw => true) true rescue Twitter::Error::NotFound, Twitter::Error::Forbidden false end # Returns the members of the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/members # @rate_limited Yes # @requires_authentication Yes # @overload list_members(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the members of the authenticated user's "presidents" list # Twitter.list_members('presidents') # Twitter.list_members(8863586) # @overload list_members(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the members of @sferik's "presidents" list # Twitter.list_members('sferik', 'presidents') # Twitter.list_members('sferik', 8863586) # Twitter.list_members(7505382, 'presidents') # Twitter.list_members(7505382, 8863586) def list_members(*args) options = {:cursor => -1}.merge(args.last.is_a?(Hash) ? args.pop : {}) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end cursor = get("/1/lists/members.json", options) Twitter::Cursor.new(cursor, 'users', Twitter::User) end # Add a member to a list # # @see https://dev.twitter.com/docs/api/1/post/lists/members/create # @note Lists are limited to having 500 members. # @rate_limited No # @requires_authentication Yes # @overload list_add_member(list, user_to_add, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_add [Integer, String] The user id or screen name to add to the list. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Add @BarackObama to the authenticated user's "presidents" list # Twitter.list_add_member('presidents', 813286) # Twitter.list_add_member(8863586, 813286) # @overload list_add_member(user, list, user_to_add, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param user_to_add [Integer, String] The user id or screen name to add to the list. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Add @BarackObama to @sferik's "presidents" list # Twitter.list_add_member('sferik', 'presidents', 813286) # Twitter.list_add_member('sferik', 8863586, 813286) # Twitter.list_add_member(7505382, 'presidents', 813286) # Twitter.list_add_member(7505382, 8863586, 813286) def list_add_member(*args) options = args.last.is_a?(Hash) ? args.pop : {} user_to_add = args.pop options.merge_user!(user_to_add) list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/members/create.json", options) Twitter::List.new(list) end # Deletes the specified list # # @see https://dev.twitter.com/docs/api/1/post/lists/destroy # @note Must be owned by the authenticated user. # @rate_limited No # @requires_authentication Yes # @overload list_destroy(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The deleted list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Delete the authenticated user's "presidents" list # Twitter.list_destroy('presidents') # Twitter.list_destroy(8863586) # @overload list_destroy(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The deleted list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Delete @sferik's "presidents" list # Twitter.list_destroy('sferik', 'presidents') # Twitter.list_destroy('sferik', 8863586) # Twitter.list_destroy(7505382, 'presidents') # Twitter.list_destroy(7505382, 8863586) def list_destroy(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = delete("/1/lists/destroy.json", options) Twitter::List.new(list) end # Updates the specified list # # @see https://dev.twitter.com/docs/api/1/post/lists/update # @rate_limited No # @requires_authentication Yes # @overload list_update(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [String] :mode ('public') Whether your list is public or private. Values can be 'public' or 'private'. # @option options [String] :description The description to give the list. # @return [Twitter::List] The created list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Update the authenticated user's "presidents" list to have the description "Presidents of the United States of America" # Twitter.list_update('presidents', :description => "Presidents of the United States of America") # Twitter.list_update(8863586, :description => "Presidents of the United States of America") # @overload list_update(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @option options [String] :mode ('public') Whether your list is public or private. Values can be 'public' or 'private'. # @option options [String] :description The description to give the list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Twitter::List] The created list. # @example Update the @sferik's "presidents" list to have the description "Presidents of the United States of America" # Twitter.list_update('sferik', 'presidents', :description => "Presidents of the United States of America") # Twitter.list_update(7505382, 'presidents', :description => "Presidents of the United States of America") # Twitter.list_update('sferik', 8863586, :description => "Presidents of the United States of America") # Twitter.list_update(7505382, 8863586, :description => "Presidents of the United States of America") def list_update(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = post("/1/lists/update.json", options) Twitter::List.new(list) end # Creates a new list for the authenticated user # # @see https://dev.twitter.com/docs/api/1/post/lists/create # @note Accounts are limited to 20 lists. # @rate_limited No # @requires_authentication Yes # @param name [String] The name for the list. # @param options [Hash] A customizable set of options. # @option options [String] :mode ('public') Whether your list is public or private. Values can be 'public' or 'private'. # @option options [String] :description The description to give the list. # @return [Twitter::List] The created list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Create a list named 'presidents' # Twitter.list_create('presidents') def list_create(name, options={}) list = post("/1/lists/create.json", options.merge(:name => name)) Twitter::List.new(list) end # List the lists of the specified user # # @see https://dev.twitter.com/docs/api/1/get/lists # @note Private lists will be included if the authenticated user is the same as the user whose lists are being returned. # @rate_limited Yes # @requires_authentication Yes # @overload lists(options={}) # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List the authenticated user's lists # Twitter.lists # @overload lists(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example List @sferik's lists # Twitter.lists('sferik') # Twitter.lists(7505382) def lists(*args) options = {:cursor => -1}.merge(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop options.merge_user!(user) if user cursor = get("/1/lists.json", options) Twitter::Cursor.new(cursor, 'lists', Twitter::List) end # Show the specified list # # @see https://dev.twitter.com/docs/api/1/get/lists/show # @note Private lists will only be shown if the authenticated user owns the specified list. # @rate_limited Yes # @requires_authentication Yes # @overload list(list, options={}) # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Show the authenticated user's "presidents" list # Twitter.list('presidents') # Twitter.list(8863586) # @overload list(user, list, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param list [Integer, String, Twitter::List] A Twitter list ID, slug, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::List] The specified list. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Show @sferik's "presidents" list # Twitter.list('sferik', 'presidents') # Twitter.list('sferik', 8863586) # Twitter.list(7505382, 'presidents') # Twitter.list(7505382, 8863586) def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} list = args.pop options.merge_list!(list) unless options[:owner_id] || options[:owner_screen_name] owner = args.pop || self.current_user.screen_name options.merge_owner!(owner) end list = get("/1/lists/show.json", options) Twitter::List.new(list) end # Returns the top 10 trending topics for a specific WOEID # # @see https://dev.twitter.com/docs/api/1/get/trends/:woeid # @rate_limited Yes # @requires_authentication No # @param woeid [Integer] The {https://developer.yahoo.com/geo/geoplanet Yahoo! Where On Earth ID} of the location to return trending information for. WOEIDs can be retrieved by calling {Twitter::Client::LocalTrends#trend_locations}. Global information is available by using 1 as the WOEID. # @param options [Hash] A customizable set of options. # @option options [String] :exclude Setting this equal to 'hashtags' will remove all hashtags from the trends list. # @return [Array<Twitter::Trend>] # @example Return the top 10 trending topics for San Francisco # Twitter.local_trends(2487956) def local_trends(woeid=1, options={}) get("/1/trends/#{woeid}.json", options).first['trends'].map do |trend| Twitter::Trend.new(trend) end end alias :trends :local_trends # Returns the locations that Twitter has trending topic information for # # @see https://dev.twitter.com/docs/api/1/get/trends/available # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @option options [Float] :lat If provided with a :long option the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for latitude are -90.0 to +90.0 (North is positive) inclusive. # @option options [Float] :long If provided with a :lat option the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude are -180.0 to +180.0 (East is positive) inclusive. # @return [Array<Twitter::Place>] # @example Return the locations that Twitter has trending topic information for # Twitter.trend_locations def trend_locations(options={}) get("/1/trends/available.json", options).map do |place| Twitter::Place.new(place) end end # Enables device notifications for updates from the specified user to the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/notifications/follow # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The specified user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Enable device notifications for updates from @sferik # Twitter.enable_notifications('sferik') # Twitter.enable_notifications(7505382) # Same as above def enable_notifications(user, options={}) options.merge_user!(user) user = post("/1/notifications/follow.json", options) Twitter::User.new(user) end # Disables notifications for updates from the specified user to the authenticating user # # @see https://dev.twitter.com/docs/api/1/post/notifications/leave # @rate_limited No # @requires_authentication Yes # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The specified user. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Disable device notifications for updates from @sferik # Twitter.disable_notifications('sferik') # Twitter.disable_notifications(7505382) # Same as above def disable_notifications(user, options={}) options.merge_user!(user) user = post("/1/notifications/leave.json", options) Twitter::User.new(user) end # Search for places that can be attached to a {Twitter::Client::Tweets#update} # # @see https://dev.twitter.com/docs/api/1/get/geo/search # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :query Free-form text to match against while executing a geo-based query, best suited for finding nearby locations by name. # @option options [String] :ip An IP address. Used when attempting to fix geolocation based off of the user's IP address. # @option options [String] :granularity ('neighborhood') This is the minimal granularity of place types to return and must be one of: 'poi', 'neighborhood', 'city', 'admin' or 'country'. # @option options [String] :accuracy ('0m') A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). # @option options [Integer] :max_results A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. # @option options [String] :contained_within This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. # @option options [String] :"attribute:street_address" This option searches for places which have this given street address. There are other well-known and application-specific attributes available. Custom attributes are also permitted. # @return [Array<Twitter::Place>] # @example Return an array of places near the IP address 172.16.58.3 # Twitter.places_nearby(:ip => "172.16.58.3") def places_nearby(options={}) get("/1/geo/search.json", options)['result']['places'].map do |place| Twitter::Place.new(place) end end alias :geo_search :places_nearby # Locates places near the given coordinates which are similar in name # # @see https://dev.twitter.com/docs/api/1/get/geo/similar_places # @note Conceptually, you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to {Twitter::Client::Geo#place} to create a new one. The token contained in the response is the token necessary to create a new place. # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :name The name a place is known as. # @option options [String] :contained_within This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. # @option options [String] :"attribute:street_address" This option searches for places which have this given street address. There are other well-known and application-specific attributes available. Custom attributes are also permitted. # @return [Array<Twitter::Place>] # @example Return an array of places similar to Twitter HQ # Twitter.places_similar(:lat => "37.7821120598956", :long => "-122.400612831116", :name => "Twitter HQ") def places_similar(options={}) get("/1/geo/similar_places.json", options)['result']['places'].map do |place| Twitter::Place.new(place) end end # Searches for up to 20 places that can be used as a place_id # # @see https://dev.twitter.com/docs/api/1/get/geo/reverse_geocode # @note This request is an informative call and will deliver generalized results about geography. # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :accuracy ('0m') A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). # @option options [String] :granularity ('neighborhood') This is the minimal granularity of place types to return and must be one of: 'poi', 'neighborhood', 'city', 'admin' or 'country'. # @option options [Integer] :max_results A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. # @return [Array<Twitter::Place>] # @example Return an array of places within the specified region # Twitter.reverse_geocode(:lat => "37.7821120598956", :long => "-122.400612831116") def reverse_geocode(options={}) get("/1/geo/reverse_geocode.json", options)['result']['places'].map do |place| Twitter::Place.new(place) end end # Returns all the information about a known place # # @see https://dev.twitter.com/docs/api/1/get/geo/id/:place_id # @rate_limited Yes # @requires_authentication No # @param place_id [String] A place in the world. These IDs can be retrieved from {Twitter::Client::Geo#reverse_geocode}. # @param options [Hash] A customizable set of options. # @return [Twitter::Place] The requested place. # @example Return all the information about Twitter HQ # Twitter.place("247f43d441defc03") def place(place_id, options={}) place = get("/1/geo/id/#{place_id}.json", options) Twitter::Place.new(place) end # Creates a new place at the given latitude and longitude # # @see https://dev.twitter.com/docs/api/1/post/geo/place # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @option options [String] :name The name a place is known as. # @option options [String] :contained_within This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. # @option options [String] :token The token found in the response from {Twitter::Client::Geo#places_similar}. # @option options [Float] :lat The latitude to search around. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude to search around. The valid range for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :"attribute:street_address" This option searches for places which have this given street address. There are other well-known and application-specific attributes available. Custom attributes are also permitted. # @return [Twitter::Place] The created place. # @example Create a new place # Twitter.place_create(:name => "@sferik's Apartment", :token => "<KEY>", :contained_within => "41bcb736f84a799e", :lat => "37.783699", :long => "-122.393581") def place_create(options={}) place = post("/1/geo/place.json", options) Twitter::Place.new(place) end # Returns the authenticated user's saved search queries # # @see https://dev.twitter.com/docs/api/1/get/saved_searches # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @return [Array<Twitter::SavedSearch>] Saved search queries. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the authenticated user's saved search queries # Twitter.saved_searches def saved_searches(options={}) get("/1/saved_searches.json", options).map do |saved_search| Twitter::SavedSearch.new(saved_search) end end # Retrieve the data for a saved search owned by the authenticating user specified by the given ID # # @see https://dev.twitter.com/docs/api/1/get/saved_searches/show/:id # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The ID of the saved search. # @param options [Hash] A customizable set of options. # @return [Twitter::SavedSearch] The saved search. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Retrieve the data for a saved search owned by the authenticating user with the ID 16129012 # Twitter.saved_search(16129012) def saved_search(id, options={}) saved_search = get("/1/saved_searches/show/#{id}.json", options) Twitter::SavedSearch.new(saved_search) end # Creates a saved search for the authenticated user # # @see https://dev.twitter.com/docs/api/1/post/saved_searches/create # @rate_limited No # @requires_authentication Yes # @param query [String] The query of the search the user would like to save. # @param options [Hash] A customizable set of options. # @return [Twitter::SavedSearch] The created saved search. # @example Create a saved search for the authenticated user with the query "twitter" # Twitter.saved_search_create("twitter") def saved_search_create(query, options={}) saved_search = post("/1/saved_searches/create.json", options.merge(:query => query)) Twitter::SavedSearch.new(saved_search) end # Destroys a saved search for the authenticated user # # @see https://dev.twitter.com/docs/api/1/post/saved_searches/destroy/:id # @note The search specified by ID must be owned by the authenticating user. # @rate_limited No # @requires_authentication Yes # @param id [Integer] The ID of the saved search. # @param options [Hash] A customizable set of options. # @return [Twitter::SavedSearch] The deleted saved search. # @example Destroys a saved search for the authenticated user with the ID 16129012 # Twitter.saved_search_destroy(16129012) def saved_search_destroy(id, options={}) saved_search = delete("/1/saved_searches/destroy/#{id}.json", options) Twitter::SavedSearch.new(saved_search) end # Returns tweets that match a specified query. # # @see https://dev.twitter.com/docs/api/1/get/search # @see https://dev.twitter.com/docs/using-search # @see https://dev.twitter.com/docs/history-rest-search-api # @note As of April 1st 2010, the Search API provides an option to retrieve "popular tweets" in addition to real-time search results. In an upcoming release, this will become the default and clients that don't want to receive popular tweets in their search results will have to explicitly opt-out. See the result_type parameter below for more information. # @rate_limited Yes # @requires_authentication No # @param q [String] A search term. # @param options [Hash] A customizable set of options. # @option options [String] :geocode Returns tweets by users located within a given radius of the given latitude/longitude. The location is preferentially taking from the Geotagging API, but will fall back to their Twitter profile. The parameter value is specified by "latitude,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers). Note that you cannot use the near operator via the API to geocode arbitrary locations; however you can use this geocode parameter to search near geocodes directly. # @option options [String] :lang Restricts tweets to the given language, given by an ISO 639-1 code. # @option options [String] :locale Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases. # @option options [Integer] :page The page number (starting at 1) to return, up to a max of roughly 1500 results (based on rpp * page). # @option options [String] :result_type Specifies what type of search results you would prefer to receive. Options are "mixed", "recent", and "popular". The current default is "mixed." # @option options [Integer] :rpp The number of tweets to return per page, up to a max of 100. # @option options [String] :until Optional. Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Boolean, String, Integer] :with_twitter_user_id When set to either true, t or 1, the from_user_id and to_user_id values in the response will map to "official" user IDs which will match those returned by the REST API. # @return [Twitter::SearchResults] Return tweets that match a specified query with search metadata # @example Returns tweets related to twitter # Twitter.search('twitter') def search(q, options={}) response = get("/search.json", options.merge(:q => q), :endpoint => search_endpoint) Twitter::SearchResults.new(response) end # Returns recent statuses related to a query with images and videos embedded # # @note Undocumented # @rate_limited Yes # @requires_authentication No # @param q [String] A search term. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @return [Array<Twitter::Status>] An array of statuses that contain videos # @example Return recent statuses related to twitter with images and videos embedded # Twitter.phoenix_search('twitter') def phoenix_search(q, options={}) get("/phoenix_search.phoenix", options.merge(:q => q))['statuses'].map do |status| Twitter::Status.new(status) end end # The user specified is blocked by the authenticated user and reported as a spammer # # @see https://dev.twitter.com/docs/api/1/post/report_spam # @rate_limited Yes # @requires_authentication No # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The reported user. # @example Report @spam for spam # Twitter.report_spam("spam") # Twitter.report_spam(14589771) # Same as above def report_spam(user, options={}) options.merge_user!(user) user = post("/1/report_spam.json", options) Twitter::User.new(user) end # @overload suggestions(options={}) # Returns the list of suggested user categories # # @see https://dev.twitter.com/docs/api/1/get/users/suggestions # @rate_limited Yes # @requires_authentication No # @param options [Hash] A customizable set of options. # @return [Array<Twitter::Suggestion>] # @example Return the list of suggested user categories # Twitter.suggestions # @overload suggestions(slug, options={}) # Returns the users in a given category # # @see https://dev.twitter.com/docs/api/1/get/users/suggestions/:slug # @rate_limited Yes # @requires_authentication No # @param slug [String] The short name of list or a category. # @param options [Hash] A customizable set of options. # @return [Array<Twitter::Suggestion>] # @example Return the users in the Art & Design category # Twitter.suggestions("art-design") def suggestions(*args) options = args.last.is_a?(Hash) ? args.pop : {} if slug = args.pop suggestion = get("/1/users/suggestions/#{slug}.json", options) Twitter::Suggestion.new(suggestion) else get("/1/users/suggestions.json", options).map do |suggestion| Twitter::Suggestion.new(suggestion) end end end # Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user # # @see https://dev.twitter.com/docs/api/1/get/users/suggestions/:slug/members # @rate_limited Yes # @requires_authentication No # @param slug [String] The short name of list or a category. # @param options [Hash] A customizable set of options. # @return [Array<Twitter::User>] # @example Return the users in the Art & Design category and their most recent status if they are not a protected user # Twitter.suggest_users("art-design") def suggest_users(slug, options={}) get("/1/users/suggestions/#{slug}/members.json", options).map do |user| Twitter::User.new(user) end end # Returns the 20 most recent statuses, including retweets if they exist, posted by the authenticating user and the users they follow # # @see https://dev.twitter.com/docs/api/1/get/statuses/home_timeline # @note This method can only return up to 800 statuses, including retweets. # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent statuses, including retweets if they exist, posted by the authenticating user and the users they follow # Twitter.home_timeline def home_timeline(options={}) get("/1/statuses/home_timeline.json", options).map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent mentions (statuses containing @username) for the authenticating user # # @see https://dev.twitter.com/docs/api/1/get/statuses/mentions # @note This method can only return up to 800 statuses. # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent mentions (statuses containing @username) for the authenticating user # Twitter.mentions def mentions(options={}) get("/1/statuses/mentions.json", options).map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent retweets posted by the specified user # # @see https://dev.twitter.com/docs/api/1/get/statuses/retweeted_by_me # @see https://dev.twitter.com/docs/api/1/get/statuses/retweeted_by_user # @rate_limited Yes # @requires_authentication Supported # @overload retweeted_by(options={}) # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent retweets posted by the authenticating user # Twitter.retweeted_by('sferik') # @overload retweeted_by(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent retweets posted by the authenticating user # Twitter.retweeted_by def retweeted_by(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) get("/1/statuses/retweeted_by_user.json", options) else get("/1/statuses/retweeted_by_me.json", options) end.map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent retweets posted by users the specified user follows # # @see https://dev.twitter.com/docs/api/1/get/statuses/retweeted_to_me # @see https://dev.twitter.com/docs/api/1/get/statuses/retweeted_to_user # @rate_limited Yes # @requires_authentication Supported # @overload retweeted_to(options={}) # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent retweets posted by users followed by the authenticating user # Twitter.retweeted_to # @overload retweeted_to(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent retweets posted by users followed by the authenticating user # Twitter.retweeted_to('sferik') def retweeted_to(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) get("/1/statuses/retweeted_to_user.json", options) else get("/1/statuses/retweeted_to_me.json", options) end.map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent tweets of the authenticated user that have been retweeted by others # # @see https://dev.twitter.com/docs/api/1/get/statuses/retweets_of_me # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent tweets of the authenticated user that have been retweeted by others # Twitter.retweets_of_me def retweets_of_me(options={}) get("/1/statuses/retweets_of_me.json", options).map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent statuses posted by the specified user # # @see https://dev.twitter.com/docs/api/1/get/statuses/user_timeline # @note This method can only return up to 3200 statuses. # @rate_limited Yes # @requires_authentication No, unless the user whose timeline you're trying to view is protected # @overload user_timeline(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @return [Array<Twitter::Status>] # @example Return the 20 most recent statuses posted by @sferik # Twitter.user_timeline('sferik') def user_timeline(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) end get("/1/statuses/user_timeline.json", options).map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent images posted by the specified user # # @see https://support.twitter.com/articles/20169409 # @note This method can only return up to the 100 most recent images. # @note Images will not be returned from tweets posted before January 1, 2010. # @rate_limited Yes # @requires_authentication No, unless the user whose timeline you're trying to view is protected # @overload media_timeline(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean] :filter Include possibly sensitive media when set to false, 'f' or 0. # @return [Array<Twitter::Status>] # @example Return the 20 most recent statuses posted by @sferik # Twitter.media_timeline('sferik') def media_timeline(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) end get("/1/statuses/media_timeline.json", options).map do |status| Twitter::Status.new(status) end end # Returns the 20 most recent statuses from the authenticating user's network # # @note Undocumented # @rate_limited Yes # @requires_authentication Yes # @param options [Hash] A customizable set of options. # @option options [Integer] :since_id Returns results with an ID greater than (that is, more recent than) the specified ID. # @option options [Integer] :max_id Returns results with an ID less than (that is, older than) or equal to the specified ID. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 200. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean, String, Integer] :exclude_replies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets - this is because the count parameter retrieves that many tweets before filtering out retweets and replies. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return the 20 most recent statuses from the authenticating user's network # Twitter.network_timeline def network_timeline(options={}) get("/i/statuses/network_timeline.json", options).map do |status| Twitter::Status.new(status) end end # Returns the top 20 trending topics for each hour in a given day # # @see https://dev.twitter.com/docs/api/1/get/trends/daily # @rate_limited Yes # @requires_authentication No # @param date [Date] The start date for the report. A 404 error will be thrown if the date is older than the available search index (7-10 days). Dates in the future will be forced to the current date. # @param options [Hash] A customizable set of options. # @option options [String] :exclude Setting this equal to 'hashtags' will remove all hashtags from the trends list. # @return [Hash] # @example Return the top 20 trending topics for each hour of October 24, 2010 # Twitter.trends_daily(Date.parse("2010-10-24")) def trends_daily(date=Date.today, options={}) trends = {} get("/1/trends/daily.json", options.merge(:date => date.strftime('%Y-%m-%d')))['trends'].each do |key, value| trends[key] = [] value.each do |trend| trends[key] << Twitter::Trend.new(trend) end end trends end # Returns the top 30 trending topics for each day in a given week # # @see https://dev.twitter.com/docs/api/1/get/trends/weekly # @rate_limited Yes # @requires_authentication No # @param date [Date] The start date for the report. A 404 error will be thrown if the date is older than the available search index (7-10 days). Dates in the future will be forced to the current date. # @param options [Hash] A customizable set of options. # @option options [String] :exclude Setting this equal to 'hashtags' will remove all hashtags from the trends list. # @return [Hash] # @example Return the top ten topics that are currently trending on Twitter # Twitter.trends_weekly(Date.parse("2010-10-24")) def trends_weekly(date=Date.today, options={}) trends = {} get("/1/trends/weekly.json", options.merge(:date => date.strftime('%Y-%m-%d')))['trends'].each do |key, value| trends[key] = [] value.each do |trend| trends[key] << Twitter::Trend.new(trend) end end trends end # Show up to 100 users who retweeted the status # # @see https://dev.twitter.com/docs/api/1/get/statuses/:id/retweeted_by # @see https://dev.twitter.com/docs/api/1/get/statuses/:id/retweeted_by/ids # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Integer] :page Specifies the page of results to retrieve. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @option options [Boolean] :ids_only ('false') Only return user ids instead of full user objects. # @return [Array] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Show up to 100 users who retweeted the status with the ID 28561922516 # Twitter.retweeters_of(28561922516) def retweeters_of(id, options={}) if ids_only = !!options.delete(:ids_only) get("/1/statuses/#{id}/retweeted_by/ids.json", options) else get("/1/statuses/#{id}/retweeted_by.json", options).map do |user| Twitter::User.new(user) end end end # Returns up to 100 of the first retweets of a given tweet # # @see https://dev.twitter.com/docs/api/1/get/statuses/retweets/:id # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Integer] :count Specifies the number of records to retrieve. Must be less than or equal to 100. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Array<Twitter::Status>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return up to 100 of the first retweets of the status with the ID 28561922516 # Twitter.retweets(28561922516) def retweets(id, options={}) get("/1/statuses/retweets/#{id}.json", options).map do |status| Twitter::Status.new(status) end end # Returns a single status, specified by ID # # @see https://dev.twitter.com/docs/api/1/get/statuses/show/:id # @rate_limited Yes # @requires_authentication No, unless the author of the status is protected # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The requested status. # @example Return the status with the ID 25938088801 # Twitter.status(25938088801) def status(id, options={}) status = get("/1/statuses/show/#{id}.json", options) Twitter::Status.new(status) end # Returns activity summary for a single status, specified by ID # # @note Undocumented # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @return [Twitter::Status] The requested status. # @example Return activity summary for the status with the ID 25938088801 # Twitter.status_activity(25938088801) def status_activity(id, options={}) status = get("/i/statuses/#{id}/activity/summary.json", options) status.merge!('id' => id) Twitter::Status.new(status) end # Returns a single status with activity summary, specified by ID # # @see https://dev.twitter.com/docs/api/1/get/statuses/show/:id # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The requested status. # @example Return the status with activity summary with the ID 25938088801 # Twitter.status_with_activity(25938088801) def status_with_activity(id, options={}) activity = get("/i/statuses/#{id}/activity/summary.json", options) status = get("/1/statuses/show/#{id}.json", options) status.merge!(activity) Twitter::Status.new(status) end # Returns an oEmbed version of a single status, specified by ID or url to the tweet # # @see https://dev.twitter.com/docs/api/1/get/statuses/oembed # @rate_limited Yes # @requires_authentication No, unless the author of the status is protected # @param id [Integer] The numerical ID of the desired status to be embedded. # @param url [String] The url to the status to be embedded. ex: https://twitter.com/#!/twitter/status/25938088801 # @param options [Hash] A customizable set of options. # @option options [Integer] :maxwidth The maximum width in pixels that the embed should be rendered at. This value is constrained to be between 250 and 550 pixels. # @option options [Boolean, String, Integer] :hide_media Specifies whether the embedded Tweet should automatically expand images which were uploaded via {https://dev.twitter.com/docs/api/1/post/statuses/update_with_media POST statuses/update_with_media}. When set to either true, t or 1 images will not be expanded. Defaults to false. # @option options [Boolean, String, Integer] :hide_thread Specifies whether the embedded Tweet should automatically show the original message in the case that the embedded Tweet is a reply. When set to either true, t or 1 the original Tweet will not be shown. Defaults to false. # @option options [Boolean, String, Integer] :omit_script Specifies whether the embedded Tweet HTML should include a `<script>` element pointing to widgets.js. In cases where a page already includes widgets.js, setting this value to true will prevent a redundant script element from being included. When set to either true, t or 1 the `<script>` element will not be included in the embed HTML, meaning that pages must include a reference to widgets.js manually. Defaults to false. # @option options [String] :align Specifies whether the embedded Tweet should be left aligned, right aligned, or centered in the page. Valid values are left, right, center, and none. Defaults to none, meaning no alignment styles are specified for the Tweet. # @option options [String] :related A value for the TWT related parameter, as described in {https://dev.twitter.com/docs/intents Web Intents}. This value will be forwarded to all Web Intents calls. # @option options [String] :lang Language code for the rendered embed. This will affect the text and localization of the rendered HTML. def oembed(id_or_url, options={}) case id_or_url when Integer id = id_or_url oembed = get("/1/statuses/oembed.json?id=#{id}", options) when String url = id_or_url escaped_url = URI.escape(url, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) oembed = get("/1/statuses/oembed.json?url=#{escaped_url}", options) end Twitter::OEmbed.new(oembed) end # Destroys the specified status # # @see https://dev.twitter.com/docs/api/1/post/statuses/destroy/:id # @note The authenticating user must be the author of the specified status. # @rate_limited No # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The deleted status. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Destroy the status with the ID 25938088801 # Twitter.status_destroy(25938088801) def status_destroy(id, options={}) status = delete("/1/statuses/destroy/#{id}.json", options) Twitter::Status.new(status) end # Retweets a tweet # # @see https://dev.twitter.com/docs/api/1/post/statuses/retweet/:id # @rate_limited Yes # @requires_authentication Yes # @param id [Integer] The numerical ID of the desired status. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The original tweet with retweet details embedded. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Retweet the status with the ID 28561922516 # Twitter.retweet(28561922516) def retweet(id, options={}) new_status = post("/1/statuses/retweet/#{id}.json", options) orig_status = new_status.delete('retweeted_status') orig_status['retweeted_status'] = new_status Twitter::Status.new(orig_status) end # Updates the authenticating user's status # # @see https://dev.twitter.com/docs/api/1/post/statuses/update # @note A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates. # @rate_limited No # @requires_authentication Yes # @param status [String] The text of your status update, up to 140 characters. # @param options [Hash] A customizable set of options. # @option options [Integer] :in_reply_to_status_id The ID of an existing status that the update is in reply to. # @option options [Float] :lat The latitude of the location this tweet refers to. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :place_id A place in the world. These IDs can be retrieved from {Twitter::Client::Geo#reverse_geocode}. # @option options [String] :display_coordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The created status. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Update the authenticating user's status # Twitter.update("I'm tweeting with @gem!") def update(status, options={}) status = post("/1/statuses/update.json", options.merge(:status => status)) Twitter::Status.new(status) end # Updates with media the authenticating user's status # # @see http://dev.twitter.com/docs/api/1/post/statuses/update_with_media # @note A status update with text/media identical to the authenticating user's current status will NOT be ignored # @requires_authentication Yes # @rate_limited No # @param status [String] The text of your status update, up to 140 characters. # @param media [File] A File object with your picture (PNG, JPEG or GIF) # @param options [Hash] A customizable set of options. # @option options [Integer] :in_reply_to_status_id The ID of an existing status that the update is in reply to. # @option options [Float] :lat The latitude of the location this tweet refers to. This option will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding :long option. # @option options [Float] :long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This option will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding :lat option. # @option options [String] :place_id A place in the world. These IDs can be retrieved from {Twitter::Client::Geo#reverse_geocode}. # @option options [String] :display_coordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from. # @option options [Boolean, String, Integer] :trim_user Each tweet returned in a timeline will include a user object with only the author's numerical ID when set to true, 't' or 1. # @return [Twitter::Status] The created status. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Update the authenticating user's status # Twitter.update_with_media("I'm tweeting with @gem!", File.new('my_awesome_pic.jpeg')) # Twitter.update_with_media("I'm tweeting with @gem!", {'io' => StringIO.new(pic), 'type' => 'jpg'}) def update_with_media(status, image, options={}) status = post("/1/statuses/update_with_media.json", options.merge('media[]' => image, 'status' => status), :endpoint => media_endpoint) Twitter::Status.new(status) end # Returns extended information for up to 100 users # # @see https://dev.twitter.com/docs/api/1/get/users/lookup # @rate_limited Yes # @requires_authentication Yes # @overload users(*users, options={}) # @param users [Array<Integer, String, Twitter::User>, Set<Integer, String, Twitter::User>] An array of Twitter user IDs, screen names, or objects. # @param options [Hash] A customizable set of options. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Array<Twitter::User>] The requested users. # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return extended information for @sferik and @pengwynn # Twitter.users('sferik', 'pengwynn') # Twitter.users(7505382, 14100886) # Same as above def users(*args) options = args.last.is_a?(Hash) ? args.pop : {} args.each_slice(MAX_USERS_PER_REQUEST).threaded_map do |users| get("/1/users/lookup.json", options.merge_users(Array(users))).map do |user| Twitter::User.new(user) end end.flatten end # Access the profile image in various sizes for the user with the indicated screen name # # @see https://dev.twitter.com/docs/api/1/get/users/profile_image/:screen_name # @rate_limited No # @requires_authentication No # @overload profile_image(options={}) # @param options [Hash] A customizable set of options. # @option options [String] :size ('normal') Specifies the size of image to fetch. Valid options include: 'bigger' (73px by 73px), 'normal' (48px by 48px), and 'mini' (24px by 24px). # @example Return the URL for the 24px by 24px version of @sferik's profile image # Twitter.profile_image(:size => 'mini') # @overload profile_image(screen_name, options={}) # @param user [String, Twitter::User] A Twitter screen name or object. # @param options [Hash] A customizable set of options. # @option options [String] :size ('normal') Specifies the size of image to fetch. Valid options include: 'bigger' (73px by 73px), 'normal' (48px by 48px), and 'mini' (24px by 24px). # @example Return the URL for the 24px by 24px version of @sferik's profile image # Twitter.profile_image('sferik', :size => 'mini') # @return [String] The URL for the requested user's profile image. def profile_image(*args) options = args.last.is_a?(Hash) ? args.pop : {} user = args.pop || self.current_user.screen_name user = user.screen_name if user.is_a?(Twitter::User) get("/1/users/profile_image/#{user}", options, :raw => true).headers['location'] end # Returns users that match the given query # # @see https://dev.twitter.com/docs/api/1/get/users/search # @rate_limited Yes # @requires_authentication Yes # @param query [String] The search query to run against people search. # @param options [Hash] A customizable set of options. # @option options [Integer] :per_page The number of people to retrieve. Maxiumum of 20 allowed per page. # @option options [Integer] :page Specifies the page of results to retrieve. # @return [Array<Twitter::User>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @example Return users that match "<NAME>" # Twitter.user_search("<NAME>") def user_search(query, options={}) get("/1/users/search.json", options.merge(:q => query)).map do |user| Twitter::User.new(user) end end # Returns extended information of a given user # # @see https://dev.twitter.com/docs/api/1/get/users/show # @rate_limited Yes # @requires_authentication No # @overload user(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @return [Twitter::User] The requested user. # @example Return extended information for @sferik # Twitter.user('sferik') # Twitter.user(7505382) # Same as above def user(*args) options = args.last.is_a?(Hash) ? args.pop : {} if user = args.pop options.merge_user!(user) user = get("/1/users/show.json", options) else user = get("/1/account/verify_credentials.json", options) end Twitter::User.new(user) end # Returns true if the specified user exists # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @return [Boolean] true if the user exists, otherwise false. # @example Return true if @sferik exists # Twitter.user?('sferik') # Twitter.user?(7505382) # Same as above # @requires_authentication No # @rate_limited Yes def user?(user, options={}) options.merge_user!(user) get("/1/users/show.json", options, :raw => true) true rescue Twitter::Error::NotFound false end # Returns an array of users that the specified user can contribute to # # @see http://dev.twitter.com/docs/api/1/get/users/contributees # @rate_limited Yes # @requires_authentication No unless requesting it from a protected user # # If getting this data of a protected user, you must authenticate (and be allowed to see that user). # @overload contributees(options={}) # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's statuses when set to true, 't' or 1. # @return [Array<Twitter::User>] # @example Return the authenticated user's contributees # Twitter.contributees # @overload contributees(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's statuses when set to true, 't' or 1. # @return [Array<Twitter::User>] # @example Return users @sferik can contribute to # Twitter.contributees('sferik') # Twitter.contributees(7505382) # Same as above def contributees(*args) options = {} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop || self.current_user.screen_name options.merge_user!(user) get("/1/users/contributees.json", options).map do |user| Twitter::User.new(user) end end # Returns an array of users who can contribute to the specified account # # @see http://dev.twitter.com/docs/api/1/get/users/contributors # @rate_limited Yes # @requires_authentication No unless requesting it from a protected user # # If getting this data of a protected user, you must authenticate (and be allowed to see that user). # @overload contributors(options={}) # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's statuses when set to true, 't' or 1. # @return [Array<Twitter::User>] # @example Return the authenticated user's contributors # Twitter.contributors # @overload contributors(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Boolean, String, Integer] :skip_status Do not include contributee's statuses when set to true, 't' or 1. # @return [Array<Twitter::User>] # @example Return users who can contribute to @sferik's account # Twitter.contributors('sferik') # Twitter.contributors(7505382) # Same as above def contributors(*args) options = {} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop || self.current_user.screen_name options.merge_user!(user) get("/1/users/contributors.json", options).map do |user| Twitter::User.new(user) end end # Returns recommended users for the authenticated user # # @note {https://dev.twitter.com/discussions/1120 Undocumented} # @rate_limited Yes # @requires_authentication Yes # @overload recommendations(options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :limit (20) Specifies the number of records to retrieve. # @option options [String] :excluded Comma-separated list of user IDs to exclude. # @example Return recommended users for the authenticated user # Twitter.recommendations # @overload recommendations(user, options={}) # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :limit (20) Specifies the number of records to retrieve. # @option options [String] :excluded Comma-separated list of user IDs to exclude. # @example Return recommended users for the authenticated user # Twitter.recommendations("sferik") # @return [Array<Twitter::User>] # @raise [Twitter::Error::Unauthorized] Error raised when supplied user credentials are not valid. def recommendations(*args) options = {} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop || self.current_user.screen_name options.merge_user!(user) options[:excluded] = options[:excluded].join(',') if options[:excluded].is_a?(Array) get("/1/users/recommendations.json", options).map do |recommendation| Twitter::User.new(recommendation['user']) end end # @note Undocumented # @rate_limited Yes # @requires_authentication Yes # # @overload following_followers_of(options={}) # Returns users following followers of the specified user # # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return users follow followers of @sferik # Twitter.following_followers_of # # @overload following_followers_of(user, options={}) # Returns users following followers of the authenticated user # # @param user [Integer, String, Twitter::User] A Twitter user ID, screen name, or object. # @param options [Hash] A customizable set of options. # @option options [Integer] :cursor (-1) Breaks the results into pages. Provide values as returned in the response objects's next_cursor and previous_cursor attributes to page back and forth in the list. # @return [Twitter::Cursor] # @example Return users follow followers of @sferik # Twitter.following_followers_of('sferik') # Twitter.following_followers_of(7505382) # Same as above def following_followers_of(*args) options = {:cursor => -1} options.merge!(args.last.is_a?(Hash) ? args.pop : {}) user = args.pop || self.current_user.screen_name options.merge_user!(user) cursor = get("/users/following_followers_of.json", options) Twitter::Cursor.new(cursor, 'users', Twitter::User) end end end
mislav/twitter
lib/twitter/list.rb
require 'twitter/creatable' require 'twitter/identifiable' require 'twitter/user' module Twitter class List < Twitter::Identifiable include Twitter::Creatable lazy_attr_reader :description, :following, :full_name, :member_count, :mode, :name, :slug, :subscriber_count, :uri alias :following? :following # @param other [Twitter::List] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end # @return [Twitter::User] def user @user ||= Twitter::User.new(@attrs['user']) unless @attrs['user'].nil? end end end
mislav/twitter
lib/twitter/mention.rb
<filename>lib/twitter/mention.rb require 'twitter/action' require 'twitter/status' require 'twitter/user' module Twitter class Mention < Twitter::Action # A collection of users who mentioned a user # # @return [Array<Twitter::User>] def sources @sources = Array(@attrs['sources']).map do |user| Twitter::User.new(user) end end # The user who mentioned a user # # @return [Twitter::User] def source @source = sources.first end # A collection of statuses that mention a user # # @return [Array<Twitter::Status>] def target_objects @target_objects = Array(@attrs['target_objects']).map do |status| Twitter::Status.new(status) end end # A collection containing the mentioned user # # @return [Array<Twitter::User>] def targets @targets = Array(@attrs['targets']).map do |user| Twitter::User.new(user) end end end end
mislav/twitter
lib/twitter/oembed.rb
require 'twitter/identifiable' module Twitter class OEmbed < Twitter::Identifiable lazy_attr_reader :author_name,:author_url, :cache_age, :height, :html, :provider_name, :provider_url, :type, :width, :url, :version end end
mislav/twitter
lib/twitter/trend.rb
require 'twitter/base' module Twitter class Trend < Twitter::Base lazy_attr_reader :events, :name, :promoted_content, :query, :url # @param other [Twitter::Trend] # @return [Boolean] def ==(other) super || (other.class == self.class && other.name == self.name) end end end
mislav/twitter
spec/twitter/media_factory_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::MediaFactory do describe ".new" do it "should generate a Photo" do media = Twitter::MediaFactory.new('type' => 'photo') media.should be_a Twitter::Photo end it "should raise an ArgumentError when type is not specified" do lambda do Twitter::MediaFactory.new({}) end.should raise_error(ArgumentError, "argument must have a 'type' key") end end end
mislav/twitter
lib/twitter/action_factory.rb
<filename>lib/twitter/action_factory.rb require 'twitter/favorite' require 'twitter/follow' require 'twitter/inflector' require 'twitter/list_member_added' require 'twitter/mention' require 'twitter/reply' require 'twitter/retweet' module Twitter class ActionFactory extend Twitter::Inflector # Instantiates a new action object # # @param attrs [Hash] # @raise [ArgumentError] Error raised when supplied argument is missing an 'action' key. # @return [Twitter::Favorite, Twitter::Follow, Twitter::ListMemberAdded, Twitter::Mention, Twitter::Reply, Twitter::Retweet] def self.new(action={}) type = action.delete('action') if type Twitter.const_get(camelize(type).to_sym).new(action) else raise ArgumentError, "argument must have an 'action' key" end end end end
mislav/twitter
spec/twitter/saved_search_spec.rb
require 'helper' describe Twitter::SavedSearch do describe "#==" do it "should return true when ids and classes are equal" do saved_search = Twitter::SavedSearch.new('id' => 1) other = Twitter::SavedSearch.new('id' => 1) (saved_search == other).should be_true end it "should return false when classes are not equal" do saved_search = Twitter::SavedSearch.new('id' => 1) other = Twitter::User.new('id' => 1) (saved_search == other).should be_false end it "should return false when ids are not equal" do saved_search = Twitter::SavedSearch.new('id' => 1) other = Twitter::SavedSearch.new('id' => 2) (saved_search == other).should be_false end end describe "#created_at" do it "should return a Time when created_at is set" do saved_search = Twitter::SavedSearch.new('created_at' => "Mon Jul 16 12:59:01 +0000 2007") saved_search.created_at.should be_a Time end it "should return nil when created_at is not set" do saved_search = Twitter::SavedSearch.new saved_search.created_at.should be_nil end end end
mislav/twitter
spec/twitter/action_factory_spec.rb
require 'helper' describe Twitter::ActionFactory do describe ".new" do it "should generate a Favorite" do action = Twitter::ActionFactory.new('action' => 'favorite') action.should be_a Twitter::Favorite end it "should generate a Follow" do action = Twitter::ActionFactory.new('action' => 'follow') action.should be_a Twitter::Follow end it "should generate a ListMemberAdded" do action = Twitter::ActionFactory.new('action' => 'list_member_added') action.should be_a Twitter::ListMemberAdded end it "should generate a Mention" do action = Twitter::ActionFactory.new('action' => 'mention') action.should be_a Twitter::Mention end it "should generate a Reply" do action = Twitter::ActionFactory.new('action' => 'reply') action.should be_a Twitter::Reply end it "should generate a Retweet" do action = Twitter::ActionFactory.new('action' => 'retweet') action.should be_a Twitter::Retweet end it "should raise an ArgumentError when action is not specified" do lambda do Twitter::ActionFactory.new({}) end.should raise_error(ArgumentError, "argument must have an 'action' key") end end end
mislav/twitter
spec/twitter/favorite_spec.rb
<reponame>mislav/twitter<filename>spec/twitter/favorite_spec.rb require 'helper' describe Twitter::Favorite do describe "#sources" do it "should return a collection of users who favorited a status" do sources = Twitter::Favorite.new('sources' => [{}]).sources sources.should be_an Array sources.first.should be_a Twitter::User end it "should be empty when not set" do sources = Twitter::Favorite.new.sources sources.should be_empty end end describe "#targets" do it "should return a collection containing the favorited status" do targets = Twitter::Favorite.new('targets' => [{}]).targets targets.should be_an Array targets.first.should be_a Twitter::Status end it "should be empty when not set" do targets = Twitter::Favorite.new.targets targets.should be_empty end end end
mislav/twitter
lib/twitter/error/not_acceptable.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 406 class Error::NotAcceptable < Twitter::Error::ClientError end end
mislav/twitter
spec/twitter/status_spec.rb
require 'helper' describe Twitter::Status do before do @old_stderr = $stderr $stderr = StringIO.new end after do $stderr = @old_stderr end describe "#==" do it "should return true when ids and classes are equal" do status = Twitter::Status.new('id' => 1) other = Twitter::Status.new('id' => 1) (status == other).should be_true end it "should return false when classes are not equal" do status = Twitter::Status.new('id' => 1) other = Twitter::User.new('id' => 1) (status == other).should be_false end it "should return false when ids are not equal" do status = Twitter::Status.new('id' => 1) other = Twitter::Status.new('id' => 2) (status == other).should be_false end end describe "#created_at" do it "should return a Time when set" do status = Twitter::Status.new('created_at' => "Mon Jul 16 12:59:01 +0000 2007") status.created_at.should be_a Time end it "should return nil when not set" do status = Twitter::Status.new status.created_at.should be_nil end end describe "#favoriters_count" do it "should return the count of favoriters when favoriters_count is set" do status = Twitter::Status.new('favoriters_count' => '1') status.favoriters_count.should be_a String status.favoriters_count.should == "1" end it "should return nil when not set" do status = Twitter::Status.new status.favoriters_count.should be_nil end end describe "#from_user" do it "should return a screen name when from_user is set" do status = Twitter::Status.new('from_user' => 'sferik') status.from_user.should be_a String status.from_user.should == "sferik" end it "should return a screen name when screen_name is set" do status = Twitter::Status.new('user' => {'screen_name' => 'sferik'}) status.from_user.should be_a String status.from_user.should == "sferik" end it "should return nil when not set" do status = Twitter::Status.new status.from_user.should be_nil end end describe "#full_text" do it "should return the text of a status" do status = Twitter::Status.new('text' => 'BOOSH') status.full_text.should be_a String status.full_text.should == "BOOSH" end it "should return the text of a status without a user" do status = Twitter::Status.new('text' => 'BOOSH', 'retweeted_status' => {'text' => 'BOOSH'}) status.full_text.should be_a String status.full_text.should == "BOOSH" end it "should return the full text of a retweeted status" do status = Twitter::Status.new('retweeted_status' => {'text' => 'BOOSH', 'user' => {'screen_name' => 'sferik'}}) status.full_text.should be_a String status.full_text.should == "RT @sferik: BOOSH" end it "should return nil when retweeted_status is not set" do status = Twitter::Status.new status.full_text.should be_nil end end describe "#geo" do it "should return a Twitter::Point when set" do status = Twitter::Status.new('geo' => {'type' => 'Point'}) status.geo.should be_a Twitter::Point end it "should return nil when not set" do status = Twitter::Status.new status.geo.should be_nil end end describe "#hashtags" do it "should return an Array of Entity::Hashtag when entities are set" do hashtags_hash = [{'text' => 'twitter', 'indices' => [10, 33]}] hashtags = Twitter::Status.new('entities' => {'hashtags' => hashtags_hash}).hashtags hashtags.should be_an Array hashtags.first.should be_an Twitter::Entity::Hashtag hashtags.first.indices.should == [10, 33] hashtags.first.text.should == 'twitter' end it "should return nil when not set" do hashtags = Twitter::Status.new.hashtags hashtags.should be_nil end it "should warn when not set" do Twitter::Status.new.hashtags $stderr.string.should =~ /To get hashtags, you must pass `:include_entities => true` when requesting the Twitter::Status\./ end end describe "#media" do it "should return media" do media = Twitter::Status.new('entities' => {'media' => [{'type' => 'photo'}]}).media media.should be_an Array media.first.should be_a Twitter::Photo end it "should return nil when not set" do media = Twitter::Status.new.media media.should be_nil end it "should warn when not set" do Twitter::Status.new.media $stderr.string.should =~ /To get media, you must pass `:include_entities => true` when requesting the Twitter::Status\./ end end describe "#metadata" do it "should return a User when user is set" do metadata = Twitter::Status.new('metadata' => {}).metadata metadata.should be_a Twitter::Metadata end it "should return nil when user is not set" do metadata = Twitter::Status.new.metadata metadata.should be_nil end end describe "#oembed" do before do stub_get("/1/statuses/oembed.json?id=25938088801"). to_return(:body => fixture("oembed.json"), :headers => {:content_type => "application/json; charset=utf-8"}) @status = Twitter::Status.new('id' => 25938088801) end it "should request the correct resource" do @status.oembed a_get("/1/statuses/oembed.json?id=25938088801"). should have_been_made end it "should return an OEmbed instance" do oembed = @status.oembed oembed.should be_a Twitter::OEmbed end context "without an id" do it "should return nil" do status = Twitter::Status.new status.oembed.should be_nil end end end describe "#place" do it "should return a Twitter::Place when set" do status = Twitter::Status.new('place' => {}) status.place.should be_a Twitter::Place end it "should return nil when not set" do status = Twitter::Status.new status.place.should be_nil end end describe "#repliers_count" do it "should return the count of favoriters when repliers_count is set" do status = Twitter::Status.new('repliers_count' => '1') status.repliers_count.should be_a String status.repliers_count.should == "1" end it "should return nil when not set" do status = Twitter::Status.new status.repliers_count.should be_nil end end describe "#retweeters_count" do it "should return the count of favoriters when retweeters_count is set" do status = Twitter::Status.new('retweeters_count' => '1') status.retweeters_count.should be_a String status.retweeters_count.should == "1" end it "should return nil when not set" do status = Twitter::Status.new status.retweeters_count.should be_nil end end describe "#retweeted_status" do it "should return a Status when retweeted_status is set" do status = Twitter::Status.new('retweeted_status' => {'text' => 'BOOSH'}) status.retweeted_status.should be_a Twitter::Status end it "should return nil when retweeted_status is not set" do status = Twitter::Status.new status.retweeted_status.should be_nil end it "should have text when retweeted_status is set" do status = Twitter::Status.new('retweeted_status' => {'text' => 'BOOSH'}) status.retweeted_status.text.should == 'BOOSH' end end describe "#urls" do it "should return an Array of Entity::Url when entities are set" do urls_hash = [{'url' => 'http://example.com/t.co', 'expanded_url' => 'http://example.com/expanded', 'display_url' => 'example.com/expanded', 'indices' => [10, 33]}] urls = Twitter::Status.new('entities' => {'urls' => urls_hash}).urls urls.should be_an Array urls.first.should be_an Twitter::Entity::Url urls.first.indices.should == [10, 33] urls.first.display_url.should == 'example.com/expanded' end it "should return nil when not set" do urls = Twitter::Status.new.urls urls.should be_nil end it "should warn when not set" do Twitter::Status.new.urls $stderr.string.should =~ /To get URLs, you must pass `:include_entities => true` when requesting the Twitter::Status\./ end end describe "#user" do it "should return a User when user is set" do user = Twitter::Status.new('user' => {}).user user.should be_a Twitter::User end it "should return nil when user is not set" do user = Twitter::Status.new.user user.should be_nil end it "should have a status when status is set" do user = Twitter::Status.new('text' => 'Tweet text.', 'user' => {}).user user.status.should be_a Twitter::Status user.status.text.should == 'Tweet text.' end end describe "#user_mentions" do it "should return an Array of Entity::User_Mention when entities are set" do user_mentions_hash = [{'screen_name'=>'sferik', 'name'=>'<NAME>', 'id_str'=>'7505382', 'indices'=>[0, 6], 'id'=>7505382}] user_mentions = Twitter::Status.new('entities' => {'user_mentions' => user_mentions_hash}).user_mentions user_mentions.should be_an Array user_mentions.first.should be_an Twitter::Entity::UserMention user_mentions.first.indices.should == [0, 6] user_mentions.first.screen_name.should == 'sferik' end it "should return nil when not set" do user_mentions = Twitter::Status.new.user_mentions user_mentions.should be_nil end it "should warn when not set" do Twitter::Status.new.user_mentions $stderr.string.should =~ /To get user mentions, you must pass `:include_entities => true` when requesting the Twitter::Status\./ end end end
mislav/twitter
spec/twitter/mention_spec.rb
require 'helper' describe Twitter::Mention do describe "#sources" do it "should return a collection of users who mentioned a user" do sources = Twitter::Mention.new('sources' => [{}]).sources sources.should be_an Array sources.first.should be_a Twitter::User end it "should be empty when not set" do sources = Twitter::Mention.new.sources sources.should be_empty end end describe "#source" do it "should return the user who mentioned a user" do source = Twitter::Mention.new('sources' => [{}]).source source.should be_a Twitter::User end it "should be nil when not set" do source = Twitter::Mention.new.source source.should be_nil end end describe "#target_objects" do it "should return a collection of statuses that mention a user" do targets = Twitter::Mention.new('target_objects' => [{}]).target_objects targets.should be_an Array targets.first.should be_a Twitter::Status end it "should be empty when not set" do targets = Twitter::Mention.new.target_objects targets.should be_empty end end describe "#targets" do it "should return a collection containing the mentioned user" do targets = Twitter::Mention.new('targets' => [{}]).targets targets.should be_an Array targets.first.should be_a Twitter::User end it "should be empty when not set" do targets = Twitter::Mention.new.targets targets.should be_empty end end end
mislav/twitter
lib/twitter/response/raise_server_error.rb
require 'faraday' require 'twitter/error/bad_gateway' require 'twitter/error/internal_server_error' require 'twitter/error/service_unavailable' module Twitter module Response class RaiseServerError < Faraday::Response::Middleware def on_complete(env) case env[:status].to_i when 500 raise Twitter::Error::InternalServerError.new("Something is technically wrong.", env[:response_headers]) when 502 raise Twitter::Error::BadGateway.new("Twitter is down or being upgraded.", env[:response_headers]) when 503 raise Twitter::Error::ServiceUnavailable.new("(__-){ Twitter is over capacity.", env[:response_headers]) end end end end end
mislav/twitter
lib/twitter/base.rb
<reponame>mislav/twitter require 'twitter/identity_map' module Twitter class Base attr_accessor :attrs alias :to_hash :attrs @@identity_map = IdentityMap.new # Define methods that retrieve the value from an initialized instance variable Hash, using the attribute as a key # # @overload self.lazy_attr_reader(attr) # @param attr [Symbol] # @overload self.lazy_attr_reader(attrs) # @param attrs [Array<Symbol>] def self.lazy_attr_reader(*attrs) attrs.each do |attribute| class_eval do define_method attribute do @attrs[attribute.to_s] end end end end def self.new(attrs={}) @@identity_map[self] ||= {} @@identity_map[self][Marshal.dump(attrs)] || super(attrs) end # Initializes a new object # # @param attrs [Hash] # @return [Twitter::Base] def initialize(attrs={}) self.update(attrs) @@identity_map[self.class][Marshal.dump(attrs)] = self end # Fetches an attribute of an object using hash notation # # @param method [String, Symbol] Message to send to the object def [](method) self.__send__(method.to_sym) rescue NoMethodError nil end # Update the attributes of an object # # @param attrs [Hash] # @return [Twitter::Base] def update(attrs) @attrs = attrs self end end end
mislav/twitter
lib/twitter/request/oauth.rb
<reponame>mislav/twitter require 'faraday' require 'simple_oauth' module Twitter module Request class TwitterOAuth < Faraday::Middleware def call(env) params = env[:body] || {} signature_params = params params.each do |key, value| signature_params = {} if value.respond_to?(:content_type) end header = SimpleOAuth::Header.new(env[:method], env[:url], signature_params, @options) env[:request_headers]['Authorization'] = header.to_s @app.call(env) end def initialize(app, options) @app, @options = app, options end end end end
mislav/twitter
lib/twitter/request/gateway.rb
require 'faraday' module Twitter module Request class Gateway < Faraday::Middleware def call(env) url = env[:url].dup url.host = @gateway env[:url] = url @app.call(env) end def initialize(app, gateway) @app, @gateway = app, gateway end end end end
mislav/twitter
lib/twitter/media_factory.rb
<gh_stars>1-10 require 'twitter/photo' module Twitter class MediaFactory # Instantiates a new media object # # @param attrs [Hash] # @raise [ArgumentError] Error raised when supplied argument is missing a 'type' key. # @return [Twitter::Photo] def self.new(media={}) type = media.delete('type') if type Twitter.const_get(type.capitalize.to_sym).new(media) else raise ArgumentError, "argument must have a 'type' key" end end end end
mislav/twitter
spec/twitter/place_spec.rb
<reponame>mislav/twitter require 'helper' describe Twitter::Place do describe "#==" do it "should return true when ids and classes are equal" do place = Twitter::Place.new('id' => 1) other = Twitter::Place.new('id' => 1) (place == other).should be_true end it "should return false when classes are not equal" do place = Twitter::Place.new('id' => 1) other = Twitter::User.new('id' => 1) (place == other).should be_false end it "should return false when ids are not equal" do place = Twitter::Place.new('id' => 1) other = Twitter::Place.new('id' => 2) (place == other).should be_false end end describe "#bounding_box" do it "should return a Twitter::Place when set" do place = Twitter::Place.new('bounding_box' => {'type' => 'Polygon', 'coordinates' => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]}) place.bounding_box.should be_a Twitter::Polygon end it "should return nil when not set" do place = Twitter::Place.new place.bounding_box.should be_nil end end describe "#country_code" do it "should return a country code when set with country_code" do place = Twitter::Place.new('country_code' => 'US') place.country_code.should == 'US' end it "should return a country code when set with countryCode" do place = Twitter::Place.new('countryCode' => 'US') place.country_code.should == 'US' end it "should return nil when not set" do place = Twitter::Place.new place.country_code.should be_nil end end describe "#parent_id" do it "should return a parent ID when set with parentid" do place = Twitter::Place.new('parentid' => 1) place.parent_id.should == 1 end it "should return nil when not set" do place = Twitter::Place.new place.parent_id.should be_nil end end describe "#place_type" do it "should return a place type when set with place_type" do place = Twitter::Place.new('place_type' => 'city') place.place_type.should == 'city' end it "should return a place type when set with placeType[name]" do place = Twitter::Place.new('placeType' => {'name' => 'Town'}) place.place_type.should == 'Town' end it "should return nil when not set" do place = Twitter::Place.new place.place_type.should be_nil end end end
mislav/twitter
lib/twitter/error/not_found.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 404 class Error::NotFound < Twitter::Error::ClientError end end
mislav/twitter
spec/twitter/list_spec.rb
require 'helper' describe Twitter::List do describe "#==" do it "should return true when ids and classes are equal" do list = Twitter::List.new('id' => 1) other = Twitter::List.new('id' => 1) (list == other).should be_true end it "should return false when classes are not equal" do list = Twitter::List.new('id' => 1) other = Twitter::User.new('id' => 1) (list == other).should be_false end it "should return false when ids are not equal" do list = Twitter::List.new('id' => 1) other = Twitter::List.new('id' => 2) (list == other).should be_false end end describe "#created_at" do it "should return a Time when created_at is set" do user = Twitter::List.new('created_at' => "Mon Jul 16 12:59:01 +0000 2007") user.created_at.should be_a Time end it "should return nil when created_at is not set" do user = Twitter::List.new user.created_at.should be_nil end end describe "#user" do it "should return a User when user is set" do user = Twitter::List.new('user' => {}).user user.should be_a Twitter::User end it "should return nil when status is not set" do user = Twitter::List.new.user user.should be_nil end end end
mislav/twitter
spec/twitter/connection_spec.rb
require 'helper' describe Twitter::Connection do subject do client = Twitter::Client.new client.class_eval{ public *Twitter::Connection.private_instance_methods } client end describe "#connection" do let(:endpoint){ URI.parse("https://api.tweeter.com") } it "returns a Faraday connection" do subject.connection.should be_a(Faraday::Connection) end it "memoizes the connection" do c1, c2 = subject.connection, subject.connection c1.object_id.should == c2.object_id end it "optionally sets a custom endpoint" do connection = subject.connection(:endpoint => endpoint) connection.url_prefix.should == endpoint end it "memoizes connections, respecting different options" do c1, c2 = subject.connection(:endpoint => endpoint), subject.connection c1.object_id.should_not == c2.object_id c3 = subject.connection(:endpoint => endpoint) c3.object_id.should == c1.object_id end end end
mislav/twitter
lib/twitter/error/bad_request.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 400 class Error::BadRequest < Twitter::Error::ClientError end end
mislav/twitter
lib/twitter/photo.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'twitter/identifiable' require 'twitter/size' module Twitter class Photo < Twitter::Identifiable lazy_attr_reader :display_url, :expanded_url, :indices, :media_url, :media_url_https, :url # @param other [Twitter::Photo] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end # @return [Array<Twitter::Size>] def sizes @sizes ||= Array(@attrs['sizes']).inject({}) do |object, (key, value)| object[key] = Twitter::Size.new(value) object end end end end
mislav/twitter
lib/twitter/inflector.rb
<reponame>mislav/twitter<gh_stars>1-10 module Twitter module Inflector # Converts a snake_case string to CamelCase # # @params string [String] # @return [String] def camelize(string) string.split('_').map(&:capitalize).join end end end
mislav/twitter
spec/twitter/client/direct_messages_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#direct_messages" do before do stub_get("/1/direct_messages.json"). to_return(:body => fixture("direct_messages.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.direct_messages a_get("/1/direct_messages.json"). should have_been_made end it "should return the 20 most recent direct messages sent to the authenticating user" do direct_messages = @client.direct_messages direct_messages.should be_an Array direct_messages.first.should be_a Twitter::DirectMessage direct_messages.first.sender.name.should == "<NAME>" end end describe "#direct_messages_sent" do before do stub_get("/1/direct_messages/sent.json"). to_return(:body => fixture("direct_messages.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.direct_messages_sent a_get("/1/direct_messages/sent.json"). should have_been_made end it "should return the 20 most recent direct messages sent by the authenticating user" do direct_messages = @client.direct_messages_sent direct_messages.should be_an Array direct_messages.first.should be_a Twitter::DirectMessage direct_messages.first.sender.name.should == "<NAME>" end end describe "#direct_message_destroy" do before do stub_delete("/1/direct_messages/destroy/1825785544.json"). to_return(:body => fixture("direct_message.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.direct_message_destroy(1825785544) a_delete("/1/direct_messages/destroy/1825785544.json"). should have_been_made end it "should return the deleted message" do direct_message = @client.direct_message_destroy(1825785544) direct_message.should be_a Twitter::DirectMessage direct_message.text.should == "Creating a fixture for the Twitter gem" end end describe "#direct_message_create" do before do stub_post("/1/direct_messages/new.json"). with(:body => {:screen_name => "pengwynn", :text => "Creating a fixture for the Twitter gem"}). to_return(:body => fixture("direct_message.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.direct_message_create("pengwynn", "Creating a fixture for the Twitter gem") a_post("/1/direct_messages/new.json"). with(:body => {:screen_name => "pengwynn", :text => "Creating a fixture for the Twitter gem"}). should have_been_made end it "should return the sent message" do direct_message = @client.direct_message_create("pengwynn", "Creating a fixture for the Twitter gem") direct_message.should be_a Twitter::DirectMessage direct_message.text.should == "Creating a fixture for the Twitter gem" end end describe "#direct_message" do before do stub_get("/1/direct_messages/show/1825786345.json"). to_return(:body => fixture("direct_message.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.direct_message(1825786345) a_get("/1/direct_messages/show/1825786345.json"). should have_been_made end it "should return the 20 most recent direct messages sent to the authenticating user" do direct_messages = @client.direct_message(1825786345) direct_messages.should be_a Twitter::DirectMessage direct_messages.sender.name.should == "<NAME>" end end end
mislav/twitter
spec/twitter/trend_spec.rb
require 'helper' describe Twitter::Trend do before do @trend = Twitter::Trend.new('name' => '#sevenwordsaftersex') end describe "#==" do it "should return true when names are equal" do other = Twitter::Trend.new('name' => '#sevenwordsaftersex') (@trend == other).should be_true end it "should return false when coordinates are not equal" do other = Twitter::Trend.new('name' => '#sixwordsaftersex') (@trend == other).should be_false end end end
mislav/twitter
spec/twitter/client/activity_spec.rb
<reponame>mislav/twitter<filename>spec/twitter/client/activity_spec.rb require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#about_me" do before do stub_get("/i/activity/about_me.json"). to_return(:body => fixture("about_me.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.activity_about_me a_get("/i/activity/about_me.json"). should have_been_made end it "should return activity about me" do activity_about_me = @client.activity_about_me activity_about_me.first.should be_a Twitter::Mention end end describe "#by_friends" do before do stub_get("/i/activity/by_friends.json"). to_return(:body => fixture("by_friends.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.activity_by_friends a_get("/i/activity/by_friends.json"). should have_been_made end it "should return activity by friends" do activity_by_friends = @client.activity_by_friends activity_by_friends.first.should be_a Twitter::Favorite end end end
mislav/twitter
twitter.gemspec
<reponame>mislav/twitter # encoding: utf-8 require File.expand_path('../lib/twitter/version', __FILE__) Gem::Specification.new do |gem| gem.add_dependency 'faraday', '~> 0.8' gem.add_dependency 'multi_json', '~> 1.3' gem.add_dependency 'simple_oauth', '~> 0.1.6' gem.add_development_dependency 'json' gem.add_development_dependency 'maruku' gem.add_development_dependency 'rake' gem.add_development_dependency 'rspec' gem.add_development_dependency 'simplecov' gem.add_development_dependency 'webmock' gem.add_development_dependency 'yard' gem.authors = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] gem.description = %q{A Ruby wrapper for the Twitter API.} gem.email = ['<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>'] gem.files = %w(LICENSE.md README.md Rakefile twitter.gemspec) gem.files += Dir.glob("lib/**/*.rb") gem.files += Dir.glob("spec/**/*") gem.homepage = 'https://github.com/jnunemaker/twitter' gem.name = 'twitter' gem.require_paths = ['lib'] gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') gem.summary = %q{Twitter API wrapper} gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.test_files = Dir.glob("spec/**/*") gem.version = Twitter::Version.to_s end
mislav/twitter
spec/twitter/direct_message_spec.rb
<filename>spec/twitter/direct_message_spec.rb require 'helper' describe Twitter::DirectMessage do describe "#==" do it "should return true when ids and classes are equal" do direct_message = Twitter::DirectMessage.new('id' => 1) other = Twitter::DirectMessage.new('id' => 1) (direct_message == other).should be_true end it "should return false when classes are not equal" do direct_message = Twitter::DirectMessage.new('id' => 1) other = Twitter::User.new('id' => 1) (direct_message == other).should be_false end it "should return false when ids are not equal" do direct_message = Twitter::DirectMessage.new('id' => 1) other = Twitter::DirectMessage.new('id' => 2) (direct_message == other).should be_false end end describe "#created_at" do it "should return a Time when created_at is set" do direct_message = Twitter::DirectMessage.new('created_at' => "Mon Jul 16 12:59:01 +0000 2007") direct_message.created_at.should be_a Time end it "should return nil when created_at is not set" do direct_message = Twitter::DirectMessage.new direct_message.created_at.should be_nil end end describe "#recipient" do it "should return a User when recipient is set" do recipient = Twitter::DirectMessage.new('recipient' => {}).recipient recipient.should be_a Twitter::User end it "should return nil when status is not set" do recipient = Twitter::DirectMessage.new.recipient recipient.should be_nil end end describe "#sender" do it "should return a User when sender is set" do sender = Twitter::DirectMessage.new('sender' => {}).sender sender.should be_a Twitter::User end it "should return nil when status is not set" do sender = Twitter::DirectMessage.new.sender sender.should be_nil end end end
mislav/twitter
spec/twitter/client/suggested_users_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#suggestions" do context "with a category slug passed" do before do stub_get("/1/users/suggestions/art-design.json"). to_return(:body => fixture("category.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.suggestions("art-design") a_get("/1/users/suggestions/art-design.json"). should have_been_made end it "should return the users in a given category of the Twitter suggested user list" do suggestion = @client.suggestions("art-design") suggestion.should be_a Twitter::Suggestion suggestion.name.should == "Art & Design" suggestion.users.should be_an Array suggestion.users.first.should be_a Twitter::User end end context "without arguments passed" do before do stub_get("/1/users/suggestions.json"). to_return(:body => fixture("suggestions.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.suggestions a_get("/1/users/suggestions.json"). should have_been_made end it "should return the list of suggested user categories" do suggestions = @client.suggestions suggestions.should be_an Array suggestions.first.should be_a Twitter::Suggestion suggestions.first.name.should == "Art & Design" end end end describe "#suggest_users" do before do stub_get("/1/users/suggestions/art-design/members.json"). to_return(:body => fixture("members.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.suggest_users("art-design") a_get("/1/users/suggestions/art-design/members.json"). should have_been_made end it "should return users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user" do suggest_users = @client.suggest_users("art-design") suggest_users.should be_a Array suggest_users.first.should be_a Twitter::User suggest_users.first.name.should == "OMGFacts" end end end
mislav/twitter
lib/twitter/error.rb
module Twitter # Custom error class for rescuing from all Twitter errors class Error < StandardError attr_reader :http_headers # Initializes a new Error object # # @param message [String] # @param http_headers [Hash] # @return [Twitter::Error] def initialize(message, http_headers) @http_headers = Hash[http_headers] super(message) end # @return [Time] def ratelimit_reset Time.at(@http_headers.values_at('x-ratelimit-reset', 'X-RateLimit-Reset').detect{|value| value}.to_i) end # @return [Integer] def ratelimit_limit @http_headers.values_at('x-ratelimit-limit', 'X-RateLimit-Limit').detect{|value| value}.to_i end # @return [Integer] def ratelimit_remaining @http_headers.values_at('x-ratelimit-remaining', 'X-RateLimit-Remaining').detect{|value| value}.to_i end # @return [Integer] def retry_after [(ratelimit_reset - Time.now).ceil, 0].max end end end
mislav/twitter
spec/twitter/cursor_spec.rb
<filename>spec/twitter/cursor_spec.rb<gh_stars>1-10 require 'helper' describe Twitter::Cursor do describe "#first?" do context "when previous cursor equals zero" do before do @cursor = Twitter::Cursor.new({'previous_cursor' => 0}, 'ids') end it "should return true" do @cursor.first?.should be_true end end context "when previous cursor does not equal zero" do before do @cursor = Twitter::Cursor.new({'previous_cursor' => 1}, 'ids') end it "should return true" do @cursor.first?.should be_false end end end describe "#last?" do context "when next cursor equals zero" do before do @cursor = Twitter::Cursor.new({'next_cursor' => 0}, 'ids') end it "should return true" do @cursor.last?.should be_true end end context "when next cursor does not equal zero" do before do @cursor = Twitter::Cursor.new({'next_cursor' => 1}, 'ids') end it "should return false" do @cursor.last?.should be_false end end end end
mislav/twitter
lib/twitter/error/unauthorized.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 401 class Error::Unauthorized < Twitter::Error::ClientError end end
mislav/twitter
lib/twitter/saved_search.rb
require 'twitter/creatable' require 'twitter/identifiable' module Twitter class SavedSearch < Twitter::Identifiable include Twitter::Creatable lazy_attr_reader :name, :position, :query # @param other [Twitter::SavedSearch] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end end end
mislav/twitter
spec/twitter/settings_spec.rb
require 'helper' describe Twitter::Settings do describe "#trend_location" do it "should return a Twitter::Place when set" do place = Twitter::Settings.new('trend_location' => [{'countryCode' => 'US', 'name' => 'San Francisco', 'country' => 'United States', 'placeType' => {'name' => 'Town', 'code' => 7}, 'woeid' => 2487956, 'parentid' => 23424977, 'url' => 'http://where.yahooapis.com/v1/place/2487956'}]) place.trend_location.should be_a Twitter::Place end it "should return nil when not set" do place = Twitter::Settings.new place.trend_location.should be_nil end end end
mislav/twitter
spec/twitter/client/favorites_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#favorites" do context "with a screen name passed" do before do stub_get("/1/favorites/sferik.json"). to_return(:body => fixture("favorites.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.favorites("sferik") a_get("/1/favorites/sferik.json"). should have_been_made end it "should return the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter" do favorites = @client.favorites("sferik") favorites.should be_an Array favorites.first.should be_a Twitter::Status favorites.first.user.name.should == "<NAME>" end end context "without arguments passed" do before do stub_get("/1/favorites.json"). to_return(:body => fixture("favorites.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.favorites a_get("/1/favorites.json"). should have_been_made end it "should return the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter" do favorites = @client.favorites favorites.should be_an Array favorites.first.should be_a Twitter::Status favorites.first.user.name.should == "<NAME>" end end end describe "#favorite" do before do stub_post("/1/favorites/create/25938088801.json"). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.favorite(25938088801) a_post("/1/favorites/create/25938088801.json"). should have_been_made end it "should return the favorite status when successful" do status = @client.favorite(25938088801) status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" end end describe "#unfavorite" do before do stub_delete("/1/favorites/destroy/25938088801.json"). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.unfavorite(25938088801) a_delete("/1/favorites/destroy/25938088801.json"). should have_been_made end it "should return the un-favorite status when successful" do status = @client.unfavorite(25938088801) status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" end end end
mislav/twitter
spec/twitter/client/tweets_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#retweeters_of" do context "with ids_only passed" do before do stub_get("/1/statuses/27467028175/retweeted_by/ids.json"). to_return(:body => fixture("ids.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeters_of(27467028175, :ids_only => true) a_get("/1/statuses/27467028175/retweeted_by/ids.json"). should have_been_made end it "should return an array of numeric user IDs of retweeters of a status" do ids = @client.retweeters_of(27467028175, :ids_only => true) ids.should be_an Array ids.first.should == 47 end end context "without ids_only passed" do before do stub_get("/1/statuses/27467028175/retweeted_by.json"). to_return(:body => fixture("retweeters_of.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeters_of(27467028175) a_get("/1/statuses/27467028175/retweeted_by.json"). should have_been_made end it "should return an array of user of retweeters of a status" do users = @client.retweeters_of(27467028175) users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end end describe "#retweets" do before do stub_get("/1/statuses/retweets/28561922516.json"). to_return(:body => fixture("retweets.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweets(28561922516) a_get("/1/statuses/retweets/28561922516.json"). should have_been_made end it "should return up to 100 of the first retweets of a given tweet" do statuses = @client.retweets(28561922516) statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "RT @gruber: As for the Series, I'm for the Giants. Fuck Texas, fuck Nol<NAME>, fuck George Bush." end end describe "#status" do before do stub_get("/1/statuses/show/25938088801.json"). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.status(25938088801) a_get("/1/statuses/show/25938088801.json"). should have_been_made end it "should return a single status" do status = @client.status(25938088801) status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" end end describe "#status_activity" do before do stub_get("/i/statuses/25938088801/activity/summary.json"). to_return(:body => fixture("activity_summary.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.status_activity(25938088801) a_get("/i/statuses/25938088801/activity/summary.json"). should have_been_made end it "should return a single status" do status = @client.status_activity(25938088801) status.should be_a Twitter::Status status.retweeters_count.should == "1" end end describe "#status_with_activity" do before do stub_get("/i/statuses/25938088801/activity/summary.json"). to_return(:body => fixture("activity_summary.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/statuses/show/25938088801.json"). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.status_with_activity(25938088801) a_get("/i/statuses/25938088801/activity/summary.json"). should have_been_made a_get("/1/statuses/show/25938088801.json"). should have_been_made end it "should return a single status" do status = @client.status_with_activity(25938088801) status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" status.retweeters_count.should == "1" end end describe "#status_destroy" do before do stub_delete("/1/statuses/destroy/25938088801.json"). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.status_destroy(25938088801) a_delete("/1/statuses/destroy/25938088801.json"). should have_been_made end it "should return a single status" do status = @client.status_destroy(25938088801) status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" end end describe "#retweet" do before do stub_post("/1/statuses/retweet/28561922516.json"). to_return(:body => fixture("retweet.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweet(28561922516) a_post("/1/statuses/retweet/28561922516.json"). should have_been_made end it "should return the original Tweet with retweet details embedded" do status = @client.retweet(28561922516) status.should be_a Twitter::Status status.text.should == "As for the Series, I'm for the Giants. Fuck Texas, fuck Nolan Ryan, fuck George Bush." status.retweeted_status.text.should == "RT @gruber: As for the Series, I'm for the Giants. Fuck Texas, fuck Nolan Ryan, fuck George Bush." status.retweeted_status.id.should_not == status.id end end describe "#update" do before do stub_post("/1/statuses/update.json"). with(:body => {:status => "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!"}). to_return(:body => fixture("status.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update("@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!") a_post("/1/statuses/update.json"). with(:body => {:status => "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!"}). should have_been_made end it "should return a single status" do status = @client.update("@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!") status.should be_a Twitter::Status status.text.should == "@noradio working on implementing #NewTwitter API methods in the twitter gem. Twurl is making it easy. Thank you!" end end describe "#update_with_media" do before do stub_post("/1/statuses/update_with_media.json", Twitter.media_endpoint). to_return(:body => fixture("status_with_media.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.update_with_media("You always have options", fixture("me.jpeg")) a_post("/1/statuses/update_with_media.json", Twitter.media_endpoint). should have_been_made end it "should return a single status" do status = @client.update_with_media("You always have options", fixture("me.jpeg")) status.text.should include("You always have options") end it 'should return the media as an entity' do status = @client.update_with_media("You always have options", fixture("me.jpeg")) status.media.should be end end describe "#oembed" do context "with id passed" do before do stub_get("/1/statuses/oembed.json?id=25938088801"). to_return(:body => fixture("oembed.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.oembed(25938088801) a_get("/1/statuses/oembed.json?id=25938088801"). should have_been_made end it "should return an OEmbed instance" do oembed = @client.oembed(25938088801) oembed.should be_a Twitter::OEmbed end end context "with url passed" do before do stub_get("/1/statuses/oembed.json?url=https%3A%2F%2Ftwitter.com%2F%23!%2Ftwitter%2Fstatus%2F25938088801"). to_return(:body => fixture("oembed.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.oembed('https://twitter.com/#!/twitter/status/25938088801') a_get("/1/statuses/oembed.json?url=https%3A%2F%2Ftwitter.com%2F%23!%2Ftwitter%2Fstatus%2F25938088801"). should have_been_made end it "should return an OEmbed instance" do oembed = @client.oembed('https://twitter.com/#!/twitter/status/25938088801') oembed.should be_a Twitter::OEmbed end end end end
mislav/twitter
lib/twitter/identifiable.rb
require 'twitter/base' module Twitter class Identifiable < Base def self.new(attrs={}) @@identity_map[self] ||= {} attrs['id'] && @@identity_map[self][attrs['id']] ? @@identity_map[self][attrs['id']].update(attrs) : super(attrs) end # Initializes a new object # # @param attrs [Hash] # @return [Twitter::Base] def initialize(attrs={}) if attrs['id'] self.update(attrs) @@identity_map[self.class][attrs['id']] = self else super end end # @return [Integer] def id @attrs['id'] end end end
mislav/twitter
spec/twitter/client/local_trends_spec.rb
<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#local_trends" do context "with woeid passed" do before do stub_get("/1/trends/2487956.json"). to_return(:body => fixture("matching_trends.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.local_trends(2487956) a_get("/1/trends/2487956.json"). should have_been_made end it "should return the top 10 trending topics for a specific WOEID" do matching_trends = @client.local_trends(2487956) matching_trends.should be_an Array matching_trends.first.should be_a Twitter::Trend matching_trends.first.name.should == "#sevenwordsaftersex" end end context "without arguments passed" do before do stub_get("/1/trends/1.json"). to_return(:body => fixture("matching_trends.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.local_trends a_get("/1/trends/1.json"). should have_been_made end end end describe "#trend_locations" do before do stub_get("/1/trends/available.json"). to_return(:body => fixture("locations.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.trend_locations a_get("/1/trends/available.json"). should have_been_made end it "should return the locations that Twitter has trending topic information for" do locations = @client.trend_locations locations.should be_an Array locations.first.should be_a Twitter::Place locations.first.name.should == "Ireland" end end end
mislav/twitter
lib/twitter/suggestion.rb
require 'twitter/base' require 'twitter/user' module Twitter class Suggestion < Twitter::Base lazy_attr_reader :name, :size, :slug # @param other [Twitter::Suggestion] # @return [Boolean] def ==(other) super || (other.class == self.class && other.slug == self.slug) end # @return [Array<Twitter::User>] def users @users = Array(@attrs['users']).map do |user| Twitter::User.new(user) end end end end
mislav/twitter
spec/twitter/user_spec.rb
require 'helper' describe Twitter::User do describe "#==" do it "should return true when ids and classes are equal" do user = Twitter::User.new('id' => 1) other = Twitter::User.new('id' => 1) (user == other).should be_true end it "should return false when classes are not equal" do user = Twitter::User.new('id' => 1) other = Twitter::Status.new('id' => 1) (user == other).should be_false end it "should return false when ids are not equal" do user = Twitter::User.new('id' => 1) other = Twitter::User.new('id' => 2) (user == other).should be_false end end describe "#created_at" do it "should return a Time when created_at is set" do user = Twitter::User.new('created_at' => "Mon Jul 16 12:59:01 +0000 2007") user.created_at.should be_a Time end it "should return nil when created_at is not set" do user = Twitter::User.new user.created_at.should be_nil end end describe "#status" do it "should return a Status when status is set" do status = Twitter::User.new('status' => {}).status status.should be_a Twitter::Status end it "should return nil when status is not set" do status = Twitter::User.new.status status.should be_nil end it "should have a user when user is set" do status = Twitter::User.new('screen_name' => 'sferik', 'status' => {}).status status.user.should be_a Twitter::User status.user.screen_name.should == 'sferik' end end end
mislav/twitter
lib/twitter/connection.rb
require 'faraday' require 'twitter/core_ext/hash' require 'twitter/request/gateway' require 'twitter/request/multipart_with_file' require 'twitter/request/oauth' require 'twitter/response/parse_json' require 'twitter/response/raise_client_error' require 'twitter/response/raise_server_error' module Twitter module Connection private # Returns a Faraday::Connection object # # @param options [Hash] A hash of options # @return [Faraday::Connection] def connection(options={}) url = options.fetch(:endpoint, endpoint) default_options = { :headers => { :accept => 'application/json', :user_agent => user_agent, }, :proxy => proxy, :ssl => {:verify => false}, :url => url, } @connections ||= {} @connections[url] ||= Faraday.new(default_options.deep_merge(connection_options)) do |builder| builder.use Twitter::Request::MultipartWithFile builder.use Twitter::Request::TwitterOAuth, credentials if credentials? builder.use Faraday::Request::Multipart builder.use Faraday::Request::UrlEncoded builder.use Twitter::Request::Gateway, gateway if gateway builder.use Twitter::Response::RaiseClientError builder.use Twitter::Response::ParseJson builder.use Twitter::Response::RaiseServerError builder.adapter(adapter) end end end end
mislav/twitter
lib/twitter/list_member_added.rb
<gh_stars>1-10 require 'twitter/action' require 'twitter/list' require 'twitter/user' module Twitter class ListMemberAdded < Twitter::Action lazy_attr_reader :target_objects # A collection of users who added a user to a list # # @return [Array<Twitter::User>] def sources @sources = Array(@attrs['sources']).map do |user| Twitter::User.new(user) end end # A collection of lists that were added to # # @return [Array<Twitter::List>] def target_objects @target_objects = Array(@attrs['target_objects']).map do |list| Twitter::List.new(list) end end # A collection of users who were added to a list # # @return [Array<Twitter::User>] def targets @targets = Array(@attrs['targets']).map do |user| Twitter::User.new(user) end end end end
mislav/twitter
lib/twitter/response/raise_client_error.rb
require 'faraday' require 'twitter/error/bad_request' require 'twitter/error/enhance_your_calm' require 'twitter/error/forbidden' require 'twitter/error/not_acceptable' require 'twitter/error/not_found' require 'twitter/error/unauthorized' module Twitter module Response class RaiseClientError < Faraday::Response::Middleware def on_complete(env) case env[:status].to_i when 400 raise Twitter::Error::BadRequest.new(error_body(env[:body]), env[:response_headers]) when 401 raise Twitter::Error::Unauthorized.new(error_body(env[:body]), env[:response_headers]) when 403 raise Twitter::Error::Forbidden.new(error_body(env[:body]), env[:response_headers]) when 404 raise Twitter::Error::NotFound.new(error_body(env[:body]), env[:response_headers]) when 406 raise Twitter::Error::NotAcceptable.new(error_body(env[:body]), env[:response_headers]) when 420 raise Twitter::Error::EnhanceYourCalm.new(error_body(env[:body]), env[:response_headers]) end end private def error_body(body) if body.nil? '' elsif body['error'] body['error'] elsif body['errors'] first = Array(body['errors']).first if first.kind_of?(Hash) first['message'].chomp else first.chomp end end end end end end
mislav/twitter
spec/twitter/search_results_spec.rb
require 'helper' describe Twitter::SearchResults do describe "#results" do it "should contain twitter status objects" do search_results = Twitter::SearchResults.new('results' => [{'text' => 'tweet!'}]) search_results.results.should be_a Array search_results.results.first.should be_a Twitter::Status end it "should be an empty array if no search results passed" do search_results = Twitter::SearchResults.new search_results.results.should be_a Array search_results.results.should == [] end end end
mislav/twitter
lib/twitter/settings.rb
require 'twitter/base' require 'twitter/place' module Twitter class Settings < Twitter::Base lazy_attr_reader :always_use_https, :discoverable_by_email, :geo_enabled, :language, :protected, :screen_name, :show_all_inline_media, :sleep_time, :time_zone alias :protected? :protected # @return [Twitter::Place] def trend_location @trend_location ||= Twitter::Place.new(@attrs['trend_location'].first) unless @attrs['trend_location'].nil? || @attrs['trend_location'].empty? end end end
mislav/twitter
lib/twitter/reply.rb
require 'twitter/action' require 'twitter/status' require 'twitter/user' module Twitter class Reply < Twitter::Action # A collection of users who replies to a user # # @return [Array<Twitter::User>] def sources @sources = Array(@attrs['sources']).map do |user| Twitter::User.new(user) end end # A collection of statuses that reply to a user # # @return [Array<Twitter::Status>] def target_objects @target_objects = Array(@attrs['target_objects']).map do |status| Twitter::Status.new(status) end end # A collection that contains the replied-to status # # @return [Array<Twitter::Status>] def targets @targets = Array(@attrs['targets']).map do |status| Twitter::Status.new(status) end end end end
mislav/twitter
spec/twitter/suggestion_spec.rb
require 'helper' describe Twitter::Suggestion do before do @suggestion = Twitter::Suggestion.new('slug' => 'art-design') end describe "#==" do it "should return true when slugs are equal" do other = Twitter::Suggestion.new('slug' => 'art-design') (@suggestion == other).should be_true end it "should return false when coordinates are not equal" do other = Twitter::Suggestion.new('slug' => 'design-art') (@suggestion == other).should be_false end end end
fnando/botkit
lib/botkit/runner.rb
<gh_stars>1-10 # frozen_string_literal: true module Botkit class Runner attr_reader :bot, :polling def initialize(bot, polling: 1) @bot = bot @polling = polling end def call loop do tick break if bot.halt? sleep(polling) end end private def tick bot.call rescue StandardError => error bot.report_exception(error) end end end
fnando/botkit
lib/botkit/message.rb
# frozen_string_literal: true module Botkit class Message attr_reader :text, :command, :raw, :options, :channel_id, :id def initialize( text:, raw: {}, channel_id: nil, command: nil, options: {}, id: nil ) @text = text @command = command @raw = raw @channel_id = channel_id @options = options @id = id end def command? command end end end
fnando/botkit
test/test_helper.rb
# frozen_string_literal: true require "simplecov" SimpleCov.start require "bundler/setup" require "botkit" require "minitest/utils" require "minitest/autorun" require_relative "./support/fake_bot"
fnando/botkit
lib/botkit.rb
<gh_stars>1-10 # frozen_string_literal: true module Botkit require "aitch" require "signal" require "botkit/version" require "botkit/runner" require "botkit/message" require "botkit/bot" def self.run(bot, **kwargs) Runner.new(bot, **kwargs).call end end
fnando/botkit
test/support/fake_bot.rb
<reponame>fnando/botkit # frozen_string_literal: true class FakeBot < Botkit::Bot def halt? true end def call end end
fnando/botkit
lib/botkit/bot.rb
<filename>lib/botkit/bot.rb<gh_stars>1-10 # frozen_string_literal: true module Botkit class Bot include Signal # When setting `bot.halt = true`, the bot will be halted # after the current loop. attr_writer :halt def initialize @halt = false end # Detect if bot should halt himself from the loop. def halt? @halt end def call end def send_message(message) end def reply_message(_message, reply) send_message(reply) end def handle_incoming_message(message) if message.command? emit("command:#{message.command}", message) else emit("internal:message", message) end end def parse_message(input) input = input.to_s _, command, text = *input.match(%r{\A/([^ @]+)(?:@.*?bot)?(?:\s+(.*?))?\z}i) { command: command, text: command ? text : input } end def command(name, &block) on("command:#{name}", &block) end def message(&block) on("internal:message", &block) end def exception(&block) on("internal:exception", &block) end def report_exception(exception) emit("internal:exception", exception) end end end
fnando/botkit
test/botkit_test.rb
<filename>test/botkit_test.rb # frozen_string_literal: true require "test_helper" class BotkitTest < Minitest::Test test "reports failures back to the bot instance" do error = StandardError.new("Failure") bot = FakeBot.new bot.expects(:report_exception).with(error) bot.stubs(:call).raises(error) Botkit.run(bot) end test "sets interval during every loop" do bot = FakeBot.new bot.stubs(:halt?).returns(false, true) Botkit::Runner.any_instance.expects(:sleep).with(1) Botkit.run(bot) end test "triggers message event" do bot = FakeBot.new message = Botkit::Message.new(text: "TEXT") callable = -> { } bot.message(&callable) callable.expects(:call).with(message) bot.handle_incoming_message(message) end test "triggers command event" do bot = FakeBot.new message = Botkit::Message.new(**bot.parse_message("/foo TEXT")) callable = -> { } bot.command(:foo, &callable) callable.expects(:call).with(message) bot.handle_incoming_message(message) end test "triggers exception event" do bot = FakeBot.new error = StandardError.new("ERROR") callable = -> { } bot.exception(&callable) callable.expects(:call).with(error) bot.report_exception(error) end test "parses command" do bot = FakeBot.new result = bot.parse_message("/foo") assert_equal "foo", result[:command] assert_nil result[:text] end test "parses command with arguments" do bot = FakeBot.new result = bot.parse_message("/foo TEXT") assert_equal "foo", result[:command] assert_equal "TEXT", result[:text] end test "parses message" do bot = FakeBot.new result = bot.parse_message("TEXT") assert_equal "TEXT", result[:text] assert_nil result[:command] end test "parses command from Telegram" do bot = FakeBot.new result = bot.parse_message("/foo@SomeBot TEXT") assert_equal "foo", result[:command] assert_equal "TEXT", result[:text] end test "replies are sent as regular messages by default" do bot = FakeBot.new message = Botkit::Message.new(text: "TEXT") reply = Botkit::Message.new(text: "REPLY") bot.expects(:send_message).with(reply) bot.reply_message(message, reply) end test "halt? returns instance variable" do bot = Botkit::Bot.new refute bot.halt? bot.instance_variable_set(:@halt, true) assert bot.halt? end end
Shopify/money
lib/rubocop/cop/money/missing_currency.rb
<reponame>Shopify/money<gh_stars>100-1000 # frozen_string_literal: true module RuboCop module Cop module Money class MissingCurrency < Cop # `Money.new()` without a currency argument cannot guarantee correctness: # - no error raised for cross-currency computation (e.g. 5 CAD + 5 USD) # - #subunits returns wrong values for 0 and 3 decimals currencies # # @example # # bad # Money.new(123.45) # Money.new # "1,234.50".to_money # # # good # Money.new(123.45, 'CAD') # "1,234.50".to_money('CAD') # def_node_matcher :money_new, <<~PATTERN (send (const {nil? cbase} :Money) {:new :from_amount :from_cents} $...) PATTERN def_node_matcher :to_money_without_currency?, <<~PATTERN ({send csend} _ :to_money) PATTERN def_node_matcher :to_money_block?, <<~PATTERN (send _ _ (block_pass (sym :to_money))) PATTERN def on_send(node) money_new(node) do |_amount, currency_arg| return if currency_arg add_offense(node, message: 'Money is missing currency argument') end if to_money_block?(node) || to_money_without_currency?(node) add_offense(node, message: 'to_money is missing currency argument') end end alias on_csend on_send def autocorrect(node) receiver, method, _ = *node lambda do |corrector| money_new(node) do |amount, currency_arg| return if currency_arg corrector.replace( node.loc.expression, "#{receiver.source}.#{method}(#{amount&.source || 0}, #{replacement_currency})" ) end if to_money_without_currency?(node) corrector.insert_after(node.loc.expression, "(#{replacement_currency})") elsif to_money_block?(node) corrector.replace( node.loc.expression, "#{receiver.source}.#{method} { |x| x.to_money(#{replacement_currency}) }" ) end end end private def replacement_currency if cop_config['ReplacementCurrency'] "'#{cop_config['ReplacementCurrency']}'" else 'Money::NULL_CURRENCY' end end end end end end
Shopify/money
spec/rubocop_helper.rb
<filename>spec/rubocop_helper.rb<gh_stars>100-1000 # frozen_string_literal: true require_relative 'spec_helper' require 'rubocop' require 'rubocop/rspec/support' RSpec.configure do |config| config.include RuboCop::RSpec::ExpectOffense end
Shopify/money
spec/rubocop/cop/money/missing_currency_spec.rb
# frozen_string_literal: true require_relative '../../../rubocop_helper' require 'rubocop/cop/money/missing_currency' RSpec.describe RuboCop::Cop::Money::MissingCurrency do subject(:cop) { described_class.new(config) } let(:config) { RuboCop::Config.new } context 'with default configuration' do it 'registers an offense and corrects for Money.new without a currency argument' do expect_offense(<<~RUBY) Money.new(1) ^^^^^^^^^^^^ Money is missing currency argument RUBY expect_correction(<<~RUBY) Money.new(1, Money::NULL_CURRENCY) RUBY end it 'does not register an offense for Money.new with currency argument' do expect_no_offenses(<<~RUBY) Money.new(1, 'CAD') RUBY end it 'registers an offense and corrects for Money.new without a currency argument' do expect_offense(<<~RUBY) Money.new ^^^^^^^^^ Money is missing currency argument RUBY expect_correction(<<~RUBY) Money.new(0, Money::NULL_CURRENCY) RUBY end it 'registers an offense and corrects for Money.from_amount without a currency argument' do expect_offense(<<~RUBY) Money.from_amount(1) ^^^^^^^^^^^^^^^^^^^^ Money is missing currency argument RUBY expect_correction(<<~RUBY) Money.from_amount(1, Money::NULL_CURRENCY) RUBY end it 'does not register an offense for Money.from_amount with currency argument' do expect_no_offenses(<<~RUBY) Money.from_amount(1, 'CAD') RUBY end it 'registers an offense and corrects for Money.from_cents without a currency argument' do expect_offense(<<~RUBY) Money.from_cents(1) ^^^^^^^^^^^^^^^^^^^ Money is missing currency argument RUBY expect_correction(<<~RUBY) Money.from_cents(1, Money::NULL_CURRENCY) RUBY end it 'does not register an offense for Money.from_cents with currency argument' do expect_no_offenses(<<~RUBY) Money.from_cents(1, 'CAD') RUBY end it 'registers an offense and corrects for to_money without a currency argument' do expect_offense(<<~RUBY) '1'.to_money ^^^^^^^^^^^^ to_money is missing currency argument RUBY expect_correction(<<~RUBY) '1'.to_money(Money::NULL_CURRENCY) RUBY end it 'registers an offense and corrects for safe navigation to_money without a currency argument' do expect_offense(<<~RUBY) item&.to_money ^^^^^^^^^^^^^^ to_money is missing currency argument RUBY expect_correction(<<~RUBY) item&.to_money(Money::NULL_CURRENCY) RUBY end it 'does not register an offense for to_money with currency argument' do expect_no_offenses(<<~RUBY) '1'.to_money('CAD') RUBY end it 'registers an offense and corrects for to_money block pass form' do expect_offense(<<~RUBY) ['1'].map(&:to_money) ^^^^^^^^^^^^^^^^^^^^^ to_money is missing currency argument RUBY expect_correction(<<~RUBY) ['1'].map { |x| x.to_money(Money::NULL_CURRENCY) } RUBY end end context 'with ReplacementCurrency configuration' do let(:config) do RuboCop::Config.new( 'Money/MissingCurrency' => { 'ReplacementCurrency' => 'CAD' } ) end it 'corrects Money.new without currency' do new_source = autocorrect_source('Money.new(1)') expect(new_source).to eq("Money.new(1, 'CAD')") end it 'corrects Money.new without amount or currency' do new_source = autocorrect_source('Money.new') expect(new_source).to eq("Money.new(0, 'CAD')") end it 'corrects to_money without currency' do new_source = autocorrect_source('1.to_money') expect(new_source).to eq("1.to_money('CAD')") end it 'corrects to_money block pass form' do new_source = autocorrect_source("['1'].map(&:to_money)") expect(new_source).to eq("['1'].map { |x| x.to_money('CAD') }") end end end
Shopify/money
spec/spec_helper.rb
<filename>spec/spec_helper.rb # frozen_string_literal: true require 'simplecov' SimpleCov.minimum_coverage 100 SimpleCov.start do add_filter "/spec/" end $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'pry-byebug' require 'database_cleaner' require 'rails' require 'active_record' require 'money' Money.active_support_deprecator.behavior = :raise Money.default_currency = Money::Currency.new('CAD') ActiveRecord::Base.establish_connection :adapter => "sqlite3", :database => ":memory:" load File.join(File.dirname(__FILE__), "schema.rb") # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| config.order = :random # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end RSpec::Matchers.define :quack_like do match do missing_methods.empty? end failure_message do "expected #{actual.name} to respond to #{missing_methods.join(', ')}" end def missing_methods expected.instance_methods - actual.instance_methods end end def configure(default_currency: nil, legacy_json_format: nil, legacy_deprecations: nil, legacy_default_currency: nil, parser: nil) old_config = Money.config Money.config = Money::Config.new.tap do |config| config.default_currency = default_currency if default_currency config.parser = parser if parser config.legacy_json_format! if legacy_json_format config.legacy_deprecations! if legacy_deprecations config.legacy_default_currency! if legacy_default_currency end yield ensure Money.config = old_config end
Shopify/money
spec/config_spec.rb
<reponame>Shopify/money<gh_stars>100-1000 # frozen_string_literal: true require 'spec_helper' RSpec.describe "Money::Config" do describe 'legacy_deprecations' do it "respects the default currency" do configure(default_currency: 'USD', legacy_deprecations: true) do expect(Money.default_currency).to eq("USD") end end it 'defaults to not opt-in to v1' do expect(Money::Config.new.legacy_deprecations).to eq(false) end it 'legacy_deprecations returns true when opting in to v1' do configure(legacy_deprecations: true) do expect(Money.config.legacy_deprecations).to eq(true) end end it 'sets the deprecations to raise' do configure(legacy_deprecations: true) do expect { Money.deprecate("test") }.to raise_error(ActiveSupport::DeprecationException) end end it 'legacy_deprecations defaults to NULL_CURRENCY' do configure(legacy_default_currency: true) do expect(Money.config.default_currency).to eq(Money::NULL_CURRENCY) end end end describe 'parser' do it 'defaults to MoneyParser' do expect(Money::Config.new.parser).to eq(MoneyParser) end it 'can be set to a new parser' do configure(parser: AccountingMoneyParser) do expect(Money.config.parser).to eq(AccountingMoneyParser) end end end describe 'default_currency' do it 'defaults to nil' do configure do expect(Money.config.default_currency).to eq(nil) end end it 'can be set to a new currency' do configure(default_currency: 'USD') do expect(Money.config.default_currency).to eq('USD') end end end end
Shopify/money
lib/money/rails/job_argument_serializer.rb
# frozen_string_literal: true class Money module Rails class JobArgumentSerializer < ::ActiveJob::Serializers::ObjectSerializer def serialize(money) super("value" => money.value, "currency" => money.currency.iso_code) end def deserialize(hash) Money.new(hash["value"], hash["currency"]) end private def klass Money end end end end
Shopify/money
lib/money.rb
<filename>lib/money.rb # frozen_string_literal: true require_relative 'money/version' require_relative 'money/money_parser' require_relative 'money/helpers' require_relative 'money/currency' require_relative 'money/null_currency' require_relative 'money/allocator' require_relative 'money/config' require_relative 'money/money' require_relative 'money/errors' require_relative 'money/deprecations' require_relative 'money/accounting_money_parser' require_relative 'money/core_extensions' require_relative 'money_column' if defined?(ActiveRecord) require_relative 'money/railtie' if defined?(Rails::Railtie) require_relative 'rubocop/cop/money' if defined?(RuboCop)
Shopify/money
lib/money/config.rb
# frozen_string_literal: true class Money class Config attr_accessor :parser, :default_currency, :legacy_json_format, :legacy_deprecations def legacy_default_currency! @default_currency ||= Money::NULL_CURRENCY end def legacy_deprecations! @legacy_deprecations = true end def legacy_json_format! @legacy_json_format = true end def initialize @parser = MoneyParser @default_currency = nil @legacy_json_format = false @legacy_deprecations = false end end end
Shopify/money
lib/money/version.rb
<filename>lib/money/version.rb # frozen_string_literal: true class Money VERSION = "1.0.0.pre" end
Shopify/money
spec/rails/job_argument_serializer_spec.rb
<filename>spec/rails/job_argument_serializer_spec.rb # frozen_string_literal: true require "rails_spec_helper" RSpec.describe Money::Rails::JobArgumentSerializer do it "roundtrip a Money argument returns the same object" do job = MoneyTestJob.new(value: Money.new(10.21, "BRL")) serialized_job = job.serialize serialized_value = serialized_job["arguments"][0]["value"] expect(serialized_value["_aj_serialized"]).to eq("Money::Rails::JobArgumentSerializer") expect(serialized_value["value"]).to eq(BigDecimal("10.21")) expect(serialized_value["currency"]).to eq("BRL") job2 = MoneyTestJob.deserialize(serialized_job) job2.send(:deserialize_arguments_if_needed) expect(job2.arguments.first[:value]).to eq(Money.new(10.21, "BRL")) end end
Shopify/money
spec/money_spec.rb
<filename>spec/money_spec.rb # frozen_string_literal: true require 'spec_helper' require 'yaml' RSpec.describe "Money" do let (:money) { Money.new(1) } let (:amount_money) { Money.new(1.23, 'USD') } let (:non_fractional_money) { Money.new(1, 'JPY') } let (:zero_money) { Money.new(0) } it "has a version" do expect(Money::VERSION).not_to(eq(nil)) end context "default currency not set" do it "raises an error" do configure(default_currency: nil) do expect { money }.to raise_error(ArgumentError) end end end it ".zero has no currency" do expect(Money.new(0, Money::NULL_CURRENCY).currency).to be_a(Money::NullCurrency) end it ".zero is a 0$ value" do expect(Money.new(0, Money::NULL_CURRENCY)).to eq(Money.new(0)) end it "returns itself with to_money" do expect(money.to_money).to eq(money) end it "#to_money uses the provided currency when it doesn't already have one" do expect(Money.new(1).to_money('CAD')).to eq(Money.new(1, 'CAD')) end it "legacy_deprecations #to_money doesn't overwrite the money object's currency" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once expect(Money.new(1, 'USD').to_money('CAD')).to eq(Money.new(1, 'USD')) end end it "#to_money raises when changing currency" do expect{ Money.new(1, 'USD').to_money('CAD') }.to raise_error(Money::IncompatibleCurrencyError) end it "defaults to 0 when constructed with no arguments" do expect(Money.new).to eq(Money.new(0)) end it "defaults to 0 when constructed with an empty string" do expect(Money.new('')).to eq(Money.new(0)) end it "legacy_deprecations defaults to 0 when constructed with an invalid string" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once expect(Money.new('invalid', 'USD')).to eq(Money.new(0.00, 'USD')) end end it "raises when constructed with an invalid string" do expect{ Money.new('invalid') }.to raise_error(ArgumentError) end it "to_s correctly displays the right number of decimal places" do expect(money.to_s).to eq("1.00") expect(non_fractional_money.to_s).to eq("1") end it "to_formatted_s with a legacy_dollars style" do expect(amount_money.to_formatted_s(:legacy_dollars)).to eq("1.23") expect(non_fractional_money.to_formatted_s(:legacy_dollars)).to eq("1.00") end it "to_formatted_s with a amount style" do expect(amount_money.to_formatted_s(:amount)).to eq("1.23") expect(non_fractional_money.to_formatted_s(:amount)).to eq("1") end it "to_s correctly displays negative numbers" do expect((-money).to_s).to eq("-1.00") expect((-amount_money).to_s).to eq("-1.23") expect((-non_fractional_money).to_s).to eq("-1") expect((-Money.new("0.05")).to_s).to eq("-0.05") end it "to_s rounds when more fractions than currency allows" do expect(Money.new("9.999", "USD").to_s).to eq("10.00") expect(Money.new("9.889", "USD").to_s).to eq("9.89") end it "to_s does not round when fractions same as currency allows" do expect(Money.new("1.25", "USD").to_s).to eq("1.25") expect(Money.new("9.99", "USD").to_s).to eq("9.99") expect(Money.new("9.999", "BHD").to_s).to eq("9.999") end it "to_s does not round if amount is larger than float allows" do expect(Money.new("99999999999999.99", "USD").to_s).to eq("99999999999999.99") expect(Money.new("999999999999999999.99", "USD").to_s).to eq("999999999999999999.99") end it "to_formatted_s raises ArgumentError on unsupported style" do expect{ money.to_formatted_s(:some_weird_style) }.to raise_error(ArgumentError) end it "legacy_json_format makes as_json return the legacy format" do configure(legacy_json_format: true) do expect(Money.new(1, 'CAD').as_json).to eq("1.00") end end it "legacy_format correctly sets the json format" do expect(Money.new(1, 'CAD').as_json(legacy_format: true)).to eq("1.00") expect(Money.new(1, 'CAD').to_json(legacy_format: true)).to eq("1.00") end it "as_json as a json containing the value and currency" do expect(money.as_json).to eq(value: "1.00", currency: "CAD") end it "is constructable with a BigDecimal" do expect(Money.new(BigDecimal("1.23"))).to eq(Money.new(1.23)) end it "is constructable with an Integer" do expect(Money.new(3)).to eq(Money.new(3.00)) end it "is construcatable with a Float" do expect(Money.new(3.00)).to eq(Money.new(BigDecimal('3.00'))) end it "is construcatable with a String" do expect(Money.new('3.00')).to eq(Money.new(3.00)) end it "is aware of the currency" do expect(Money.new(1.00, 'CAD').currency.iso_code).to eq('CAD') end it "is addable" do expect((Money.new(1.51) + Money.new(3.49))).to eq(Money.new(5.00)) end it "keeps currency across calculations" do expect(Money.new(1, 'USD') - Money.new(1, 'USD') + Money.new(1.23, Money::NULL_CURRENCY)).to eq(Money.new(1.23, 'USD')) end it "raises error if added other is not compatible" do expect{ Money.new(5.00) + nil }.to raise_error(TypeError) end it "is able to add $0 + $0" do expect((Money.new + Money.new)).to eq(Money.new) end it "legacy_deprecations adds inconsistent currencies" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once expect(Money.new(5, 'USD') + Money.new(1, 'CAD')).to eq(Money.new(6, 'USD')) end end it "raises when adding inconsistent currencies" do expect{ Money.new(5, 'USD') + Money.new(1, 'CAD') }.to raise_error(Money::IncompatibleCurrencyError) end it "is subtractable" do expect((Money.new(5.00) - Money.new(3.49))).to eq(Money.new(1.51)) end it "raises error if subtracted other is not compatible" do expect{ Money.new(5.00) - nil }.to raise_error(TypeError) end it "is subtractable to $0" do expect((Money.new(5.00) - Money.new(5.00))).to eq(Money.new) end it "logs a deprecation warning when adding across currencies" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate) expect(Money.new(10, 'USD') - Money.new(1, 'JPY')).to eq(Money.new(9, 'USD')) end end it "keeps currency when doing a computation with a null currency" do currency = Money.new(10, 'JPY') no_currency = Money.new(1, Money::NULL_CURRENCY) expect((no_currency + currency).currency).to eq(Money::Currency.find!('JPY')) expect((currency - no_currency).currency).to eq(Money::Currency.find!('JPY')) end it "does not log a deprecation warning when adding with a null currency value" do currency = Money.new(10, 'USD') no_currency = Money.new(1, Money::NULL_CURRENCY) expect(Money).not_to receive(:deprecate) expect(no_currency + currency).to eq(Money.new(11, 'USD')) expect(currency - no_currency).to eq(Money.new(9, 'USD')) end it "is substractable to a negative amount" do expect((Money.new(0.00) - Money.new(1.00))).to eq(Money.new("-1.00")) end it "is never negative zero" do expect(Money.new(-0.00).to_s).to eq("0.00") expect((Money.new(0) * -1).to_s).to eq("0.00") end it "#inspects to a presentable string" do expect(money.inspect).to eq("#<Money value:1.00 currency:CAD>") expect(Money.new(1, 'JPY').inspect).to eq("#<Money value:1 currency:JPY>") expect(Money.new(1, 'JOD').inspect).to eq("#<Money value:1.000 currency:JOD>") end it "is inspectable within an array" do expect([money].inspect).to eq("[#<Money value:1.00 currency:CAD>]") end it "correctly support eql? as a value object" do expect(money).to eq(Money.new(1)) expect(money).to eq(Money.new(1, 'CAD')) end it "does not eql? with a non money object" do expect(money).to_not eq(1) expect(money).to_not eq(OpenStruct.new(value: 1)) end it "does not eql? when currency missmatch" do expect(money).to_not eq(Money.new(1, 'JPY')) end it "is addable with integer" do expect((Money.new(1.33) + 1)).to eq(Money.new(2.33)) expect((1 + Money.new(1.33))).to eq(Money.new(2.33)) end it "is addable with float" do expect((Money.new(1.33) + 1.50)).to eq(Money.new(2.83)) expect((1.50 + Money.new(1.33))).to eq(Money.new(2.83)) end it "is subtractable with integer" do expect((Money.new(1.66) - 1)).to eq(Money.new(0.66)) expect((2 - Money.new(1.66))).to eq(Money.new(0.34)) end it "is subtractable with float" do expect((Money.new(1.66) - 1.50)).to eq(Money.new(0.16)) expect((1.50 - Money.new(1.33))).to eq(Money.new(0.17)) end it "is multipliable with an integer" do expect((Money.new(1.00) * 55)).to eq(Money.new(55.00)) expect((55 * Money.new(1.00))).to eq(Money.new(55.00)) end it "is multiplable with a float" do expect((Money.new(1.00) * 1.50)).to eq(Money.new(1.50)) expect((1.50 * Money.new(1.00))).to eq(Money.new(1.50)) end it "is multipliable by a rational" do expect((Money.new(3.3) * Rational(1, 12))).to eq(Money.new(0.28)) expect((Rational(1, 12) * Money.new(3.3))).to eq(Money.new(0.28)) end it "is multipliable by a repeatable floating point number" do expect((Money.new(24.00) * (1 / 30.0))).to eq(Money.new(0.80)) expect(((1 / 30.0) * Money.new(24.00))).to eq(Money.new(0.80)) end it "is multipliable by a repeatable floating point number where the floating point error rounds down" do expect((Money.new(3.3) * (1.0 / 12))).to eq(Money.new(0.28)) expect(((1.0 / 12) * Money.new(3.3))).to eq(Money.new(0.28)) end it "legacy_deprecations is multipliable by a money object" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once expect((Money.new(3.3, 'USD') * Money.new(1, 'USD'))).to eq(Money.new(3.3, 'USD')) end end it "raises when multiplied by a money object" do expect{ (Money.new(3.3) * Money.new(1)) }.to raise_error(ArgumentError) end it "rounds multiplication result with fractional penny of 5 or higher up" do expect((Money.new(0.03) * 0.5)).to eq(Money.new(0.02)) expect((0.5 * Money.new(0.03))).to eq(Money.new(0.02)) end it "rounds multiplication result with fractional penny of 4 or lower down" do expect((Money.new(0.10) * 0.33)).to eq(Money.new(0.03)) expect((0.33 * Money.new(0.10))).to eq(Money.new(0.03)) end it "is less than a bigger integer" do expect(Money.new(1)).to be < 2 expect(2).to be > Money.new(1) end it "is less than or equal to a bigger integer" do expect(Money.new(1)).to be <= 2 expect(2).to be >= Money.new(1) end it "is greater than a lesser integer" do expect(Money.new(2)).to be > 1 expect(1).to be < Money.new(2) end it "is greater than or equal to a lesser integer" do expect(Money.new(2)).to be >= 1 expect(1).to be <= Money.new(2) end it "raises if divided" do expect { Money.new(55.00) / 55 }.to raise_error(RuntimeError) end it "returns cents in to_json" do configure(legacy_json_format: true) do expect(Money.new('1.23', 'USD').to_json).to eq('1.23') end end it "returns value and currency in to_json" do expect(Money.new(1.00).to_json).to eq('{"value":"1.00","currency":"CAD"}') expect(JSON.dump(Money.new(1.00, "CAD"))).to eq('{"value":"1.00","currency":"CAD"}') end it "supports absolute value" do expect(Money.new(-1.00).abs).to eq(Money.new(1.00)) end it "supports to_i" do expect(Money.new(1.50).to_i).to eq(1) end it "supports to_d" do expect(Money.new(1.29).to_d).to eq(BigDecimal('1.29')) end it "supports to_f" do expect(Money.new(1.50).to_f.to_s).to eq("1.5") end describe '#from_subunits' do it "creates Money object from an integer value in cents and currency" do expect(Money.from_subunits(1950, 'CAD')).to eq(Money.new(19.50)) end it "creates Money object from an integer value in dollars and currency with no cents" do expect(Money.from_subunits(1950, 'JPY')).to eq(Money.new(1950, 'JPY')) end describe 'with format specified' do it 'overrides the subunit_to_unit amount' do expect(Money.from_subunits(100, 'ISK', format: :stripe)).to eq(Money.new(1, 'ISK')) end it 'fallbacks to the default subunit_to_unit amount if no override is specified' do expect(Money.from_subunits(100, 'USD', format: :stripe)).to eq(Money.new(1, 'USD')) end it 'raises if the format is not found' do expect { Money.from_subunits(100, 'ISK', format: :unknown) }.to(raise_error(ArgumentError)) end end end it "raises when constructed with a NaN value" do expect { Money.new( 0.0 / 0) }.to raise_error(ArgumentError) end it "is comparable with non-money objects" do expect(money).not_to eq(nil) end it "supports floor" do expect(Money.new(15.52).floor).to eq(Money.new(15.00)) expect(Money.new(18.99).floor).to eq(Money.new(18.00)) expect(Money.new(21).floor).to eq(Money.new(21)) end it "generates a true rational" do expect(Money.rational(Money.new(10.0, 'USD'), Money.new(15.0, 'USD'))).to eq(Rational(2,3)) configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once expect(Money.rational(Money.new(10.0, 'USD'), Money.new(15.0, 'JPY'))).to eq(Rational(2,3)) end end it "does not allocate a new money object when multiplying by 1" do expect((money * 1).object_id).to eq(money.object_id) end it "does not allocate a new money object when adding 0" do expect((money + 0).object_id).to eq(money.object_id) end it "does not allocate a new money object when subtracting 0" do expect((money - 0).object_id).to eq(money.object_id) end it "does not allocate when computing absolute value when already positive" do expect((money.abs).object_id).to eq(money.object_id) end it "does not allocate when computing floor value when already floored" do expect((money.floor).object_id).to eq(money.object_id) end it "does not allocate when computing floor value when already rounded" do expect((money.round).object_id).to eq(money.object_id) end describe "frozen with amount of $1" do let (:money) { Money.new(1.00) } it "is equals to $1" do expect(money).to eq(Money.new(1.00)) end it "is not equals to $2" do expect(money).not_to eq(Money.new(2.00)) end it "<=> $1 is 0" do expect((money <=> Money.new(1.00))).to eq(0) end it "<=> $2 is -1" do expect((money <=> Money.new(2.00))).to eq(-1) end it "<=> $0.50 equals 1" do expect((money <=> Money.new(0.50))).to eq(1) end it "<=> works with non-money objects" do expect((money <=> 1)).to eq(0) expect((money <=> 2)).to eq(-1) expect((money <=> 0.5)).to eq(1) expect((1 <=> money)).to eq(0) expect((2 <=> money)).to eq(1) expect((0.5 <=> money)).to eq(-1) end it "have the same hash value as $1" do expect(money.hash).to eq(Money.new(1.00).hash) end it "does not have the same hash value as $2" do expect(money.hash).to_not eq(Money.new(2.00).hash) end end describe('Comparable') do let (:cad_05) { Money.new(5.00, 'CAD') } let (:cad_10) { Money.new(10.00, 'CAD') } let (:cad_20) { Money.new(20.00, 'CAD') } let (:nil_05) { Money.new(5.00, Money::NULL_CURRENCY) } let (:nil_10) { Money.new(10.00, Money::NULL_CURRENCY) } let (:nil_20) { Money.new(20.00, Money::NULL_CURRENCY) } let (:usd_10) { Money.new(10.00, 'USD') } it "<=> can compare with and without currency" do expect(Money.new(1000, Money::NULL_CURRENCY) <=> Money.new(2000, 'JPY')).to eq(-1) expect(Money.new(2000, 'JPY') <=> Money.new(1000, Money::NULL_CURRENCY)).to eq(1) end it "<=> issues deprecation warning when comparing incompatible currency" do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).twice expect(Money.new(1000, 'USD') <=> Money.new(2000, 'JPY')).to eq(-1) expect(Money.new(2000, 'JPY') <=> Money.new(1000, 'USD')).to eq(1) end end describe('same values') do describe('same currencies') do it { expect(cad_10 <=> cad_10).to(eq(0)) } it { expect(cad_10 > cad_10).to(eq(false)) } it { expect(cad_10 >= cad_10).to(eq(true)) } it { expect(cad_10 == cad_10).to(eq(true)) } it { expect(cad_10 <= cad_10).to(eq(true)) } it { expect(cad_10 < cad_10).to(eq(false)) } end describe('null currency') do it { expect(cad_10 <=> nil_10).to(eq(0)) } it { expect(cad_10 > nil_10).to(eq(false)) } it { expect(cad_10 >= nil_10).to(eq(true)) } it { expect(cad_10 == nil_10).to(eq(true)) } it { expect(cad_10 <= nil_10).to(eq(true)) } it { expect(cad_10 < nil_10).to(eq(false)) } end describe('legacy different currencies') do around(:each) do |test| configure(legacy_deprecations: true) { test.run } end it { expect(Money).to(receive(:deprecate).once); expect(cad_10 <=> usd_10).to(eq(0)) } it { expect(Money).to(receive(:deprecate).once); expect(cad_10 > usd_10).to(eq(false)) } it { expect(Money).to(receive(:deprecate).once); expect(cad_10 >= usd_10).to(eq(true)) } it { expect(Money).to(receive(:deprecate).once); expect(cad_10 <= usd_10).to(eq(true)) } it { expect(Money).to(receive(:deprecate).once); expect(cad_10 < usd_10).to(eq(false)) } end describe('different currencies') do it { expect(cad_10 == usd_10).to(eq(false)) } end describe('to_money types') do it { expect(cad_10 <=> 10.00).to(eq(0)) } it { expect(cad_10 > 10.00).to(eq(false)) } it { expect(cad_10 >= 10.00).to(eq(true)) } it { expect(cad_10 == 10.00).to(eq(false)) } it { expect(cad_10 <= 10.00).to(eq(true)) } it { expect(cad_10 < 10.00).to(eq(false)) } end end describe('left lower than right') do describe('same currencies') do it { expect(cad_10 <=> cad_20).to(eq(-1)) } it { expect(cad_10 > cad_20).to(eq(false)) } it { expect(cad_10 >= cad_20).to(eq(false)) } it { expect(cad_10 == cad_20).to(eq(false)) } it { expect(cad_10 <= cad_20).to(eq(true)) } it { expect(cad_10 < cad_20).to(eq(true)) } end describe('null currency') do it { expect(cad_10 <=> nil_20).to(eq(-1)) } it { expect(cad_10 > nil_20).to(eq(false)) } it { expect(cad_10 >= nil_20).to(eq(false)) } it { expect(cad_10 == nil_20).to(eq(false)) } it { expect(cad_10 <= nil_20).to(eq(true)) } it { expect(cad_10 < nil_20).to(eq(true)) } end describe('to_money types') do it { expect(cad_10 <=> 20.00).to(eq(-1)) } it { expect(cad_10 > 20.00).to(eq(false)) } it { expect(cad_10 >= 20.00).to(eq(false)) } it { expect(cad_10 == 20.00).to(eq(false)) } it { expect(cad_10 <= 20.00).to(eq(true)) } it { expect(cad_10 < 20.00).to(eq(true)) } end end describe('left greater than right') do describe('same currencies') do it { expect(cad_10 <=> cad_05).to(eq(1)) } it { expect(cad_10 > cad_05).to(eq(true)) } it { expect(cad_10 >= cad_05).to(eq(true)) } it { expect(cad_10 == cad_05).to(eq(false)) } it { expect(cad_10 <= cad_05).to(eq(false)) } it { expect(cad_10 < cad_05).to(eq(false)) } end describe('null currency') do it { expect(cad_10 <=> nil_05).to(eq(1)) } it { expect(cad_10 > nil_05).to(eq(true)) } it { expect(cad_10 >= nil_05).to(eq(true)) } it { expect(cad_10 == nil_05).to(eq(false)) } it { expect(cad_10 <= nil_05).to(eq(false)) } it { expect(cad_10 < nil_05).to(eq(false)) } end describe('to_money types') do it { expect(cad_10 <=> 5.00).to(eq(1)) } it { expect(cad_10 > 5.00).to(eq(true)) } it { expect(cad_10 >= 5.00).to(eq(true)) } it { expect(cad_10 == 5.00).to(eq(false)) } it { expect(cad_10 <= 5.00).to(eq(false)) } it { expect(cad_10 < 5.00).to(eq(false)) } end end describe('any values, non-to_money types') do it { expect(cad_10 <=> nil).to(eq(nil)) } it { expect { cad_10 > nil }.to(raise_error(ArgumentError)) } it { expect { cad_10 >= nil }.to(raise_error(ArgumentError)) } it { expect(cad_10 == nil).to(eq(false)) } it { expect { cad_10 <= nil }.to(raise_error(ArgumentError)) } it { expect { cad_10 < nil }.to(raise_error(ArgumentError)) } end end describe "#subunits" do it 'multiplies by the number of decimal places for the currency' do expect(Money.new(1, 'USD').subunits).to eq(100) expect(Money.new(1, 'JPY').subunits).to eq(1) expect(Money.new(1, 'IQD').subunits).to eq(1000) expect(Money.new(1).subunits).to eq(100) end describe 'with format specified' do it 'overrides the subunit_to_unit amount' do expect(Money.new(1, 'ISK').subunits(format: :stripe)).to eq(100) end it 'fallbacks to the default subunit_to_unit amount if no override is specified' do expect(Money.new(1, 'USD').subunits(format: :stripe)).to eq(100) end it 'raises if the format is not found' do expect { Money.new(1, 'ISK').subunits(format: :unknown) }.to(raise_error(ArgumentError)) end end end describe "value" do it "rounds to the number of minor units provided by the currency" do expect(Money.new(1.1111, 'USD').value).to eq(1.11) expect(Money.new(1.1111, 'JPY').value).to eq(1) expect(Money.new(1.1111, 'IQD').value).to eq(1.111) end end describe "with amount of $0" do let (:money) { Money.new(0) } it "is zero" do expect(money).to be_zero end it "is greater than -$1" do expect(money).to be > Money.new("-1.00") end it "is greater than or equal to $0" do expect(money).to be >= Money.new end it "is less than or equal to $0" do expect(money).to be <= Money.new end it "is less than $1" do expect(money).to be < Money.new(1.00) end end describe "with amount of $1" do let (:money) { Money.new(1.00) } it "is not zero" do expect(money).not_to be_zero end it "returns cents as a decimal value = 1.00" do expect(money.value).to eq(BigDecimal("1.00")) end it "returns cents as 100 cents" do expect(money.subunits).to eq(100) end it "is greater than $0" do expect(money).to be > Money.new(0.00) end it "is less than $2" do expect(money).to be < Money.new(2.00) end it "is equal to $1" do expect(money).to eq(Money.new(1.00)) end end describe "allocation"do specify "#allocate is calculated by Money::Allocator#allocate" do expected = [Money.new(1), [Money.new(1)]] expect_any_instance_of(Money::Allocator).to receive(:allocate).with([0.5, 0.5], :roundrobin).and_return(expected) expect(Money.new(2).allocate([0.5, 0.5])).to eq(expected) end specify "#allocate does not lose pennies (integration test)" do moneys = Money.new(0.05).allocate([0.3,0.7]) expect(moneys[0]).to eq(Money.new(0.02)) expect(moneys[1]).to eq(Money.new(0.03)) end specify "#allocate_max_amounts is calculated by Money::Allocator#allocate_max_amounts" do expected = [Money.new(1), [Money.new(1)]] expect_any_instance_of(Money::Allocator).to receive(:allocate_max_amounts).and_return(expected) expect(Money.new(2).allocate_max_amounts([0.5, 0.5])).to eq(expected) end specify "#allocate_max_amounts returns the weighted allocation without exceeding the maxima when there is room for the remainder (integration test)" do expect( Money.new(30.75).allocate_max_amounts([Money.new(26), Money.new(4.75)]), ).to eq([Money.new(26), Money.new(4.75)]) end end describe "split" do specify "#split needs at least one party" do expect {Money.new(1).split(0)}.to raise_error(ArgumentError) expect {Money.new(1).split(-1)}.to raise_error(ArgumentError) end specify "#gives 1 cent to both people if we start with 2" do expect(Money.new(0.02).split(2)).to eq([Money.new(0.01), Money.new(0.01)]) end specify "#split may distribute no money to some parties if there isnt enough to go around" do expect(Money.new(0.02).split(3)).to eq([Money.new(0.01), Money.new(0.01), Money.new(0)]) end specify "#split does not lose pennies" do expect(Money.new(0.05).split(2)).to eq([Money.new(0.03), Money.new(0.02)]) end specify "#split does not lose dollars with non-decimal currencies" do expect(Money.new(5, 'JPY').split(2)).to eq([Money.new(3, 'JPY'), Money.new(2, 'JPY')]) end specify "#split a dollar" do moneys = Money.new(1).split(3) expect(moneys[0].subunits).to eq(34) expect(moneys[1].subunits).to eq(33) expect(moneys[2].subunits).to eq(33) end specify "#split a 100 yen" do moneys = Money.new(100, 'JPY').split(3) expect(moneys[0].value).to eq(34) expect(moneys[1].value).to eq(33) expect(moneys[2].value).to eq(33) end end describe "calculate_splits" do specify "#calculate_splits gives 1 cent to both people if we start with 2" do actual = Money.new(0.02, 'CAD').calculate_splits(2) expect(actual).to eq({ Money.new(0.01, 'CAD') => 2, }) end specify "#calculate_splits gives an extra penny to one" do actual = Money.new(0.04, 'CAD').calculate_splits(3) expect(actual).to eq({ Money.new(0.02, 'CAD') => 1, Money.new(0.01, 'CAD') => 2, }) end end describe "fraction" do specify "#fraction needs a positive rate" do expect {Money.new(1).fraction(-0.5)}.to raise_error(ArgumentError) end specify "#fraction returns the amount minus a fraction" do expect(Money.new(1.15).fraction(0.15)).to eq(Money.new(1.00)) expect(Money.new(2.50).fraction(0.15)).to eq(Money.new(2.17)) expect(Money.new(35.50).fraction(0)).to eq(Money.new(35.50)) end end describe "with amount of $1 with created with 3 decimal places" do let (:money) { Money.new(1.125) } it "rounds 3rd decimal place" do expect(money.value).to eq(BigDecimal("1.13")) end end describe "parser dependency injection" do around(:each) { |test| configure(parser: AccountingMoneyParser, default_currency: 'CAD') { test.run }} it "keeps AccountingMoneyParser class on new money objects" do expect(Money.new.class.parser).to eq(AccountingMoneyParser) end it "supports parenthesis from AccountingMoneyParser" do expect(Money.parse("($5.00)")).to eq(Money.new(-5)) end it "supports parenthesis from AccountingMoneyParser for .to_money" do expect("($5.00)".to_money).to eq(Money.new(-5)) end end describe "round" do it "rounds to 0 decimal places by default" do expect(Money.new(54.1).round).to eq(Money.new(54)) expect(Money.new(54.5).round).to eq(Money.new(55)) end # Overview of standard vs. banker's rounding for next 4 specs: # http://www.xbeat.net/vbspeed/i_BankersRounding.htm it "implements standard rounding for 2 digits" do expect(Money.new(54.1754).round(2)).to eq(Money.new(54.18)) expect(Money.new(343.2050).round(2)).to eq(Money.new(343.21)) expect(Money.new(106.2038).round(2)).to eq(Money.new(106.20)) end it "implements standard rounding for 1 digit" do expect(Money.new(27.25).round(1)).to eq(Money.new(27.3)) expect(Money.new(27.45).round(1)).to eq(Money.new(27.5)) expect(Money.new(27.55).round(1)).to eq(Money.new(27.6)) end end describe "from_amount quacks like RubyMoney" do it "accepts an optional currency parameter" do expect { Money.from_amount(1, "CAD") }.to_not raise_error end it "accepts Rational number" do expect(Money.from_amount(Rational("999999999999999999.999")).value).to eql(BigDecimal("1000000000000000000", Money::Helpers::MAX_DECIMAL)) expect(Money.from_amount(Rational("999999999999999999.99")).value).to eql(BigDecimal("999999999999999999.99", Money::Helpers::MAX_DECIMAL)) end it "raises ArgumentError with unsupported argument" do expect { Money.from_amount(Object.new) }.to raise_error(ArgumentError) end end describe "YAML serialization" do it "accepts values with currencies" do money = YAML.dump(Money.new(750, 'usd')) expect(money).to eq("--- !ruby/object:Money\nvalue: '750.0'\ncurrency: USD\n") end it "does not change BigDecimal value to Integer while rounding for currencies without subunits" do money = Money.new(100, 'JPY').to_yaml expect(money).to eq("--- !ruby/object:Money\nvalue: '100.0'\ncurrency: JPY\n") end end describe "YAML deserialization" do it "accepts values with currencies" do money = YAML.load("--- !ruby/object:Money\nvalue: '750.0'\ncurrency: USD\n") expect(money).to eq(Money.new(750, 'usd')) end it "accepts values with null currencies" do money = YAML.load("--- !ruby/object:Money\nvalue: '750.0'\ncurrency: XXX\n") expect(money).to eq(Money.new(750)) end it "accepts serialized NullCurrency objects" do money = YAML.load(<<~EOS) --- !ruby/object:Money currency: !ruby/object:Money::NullCurrency symbol: >- $ disambiguate_symbol: iso_code: >- XXX iso_numeric: >- 999 name: >- No Currency smallest_denomination: 1 subunit_to_unit: 100 minor_units: 2 value: !ruby/object:BigDecimal 27:0.6935E2 cents: 6935 EOS expect(money).to eq(Money.new(69.35, Money::NULL_CURRENCY)) end it "accepts BigDecimal values" do money = YAML.load(<<~EOS) --- !ruby/object:Money value: !ruby/object:BigDecimal 18:0.75E3 cents: 75000 EOS expect(money).to be == Money.new(750) expect(money.value).to be_a BigDecimal end it "accepts old float values..." do money = YAML.load(<<~EOS) --- !ruby/object:Money value: 750.00 cents: 75000 EOS expect(money).to be == Money.new(750) expect(money.value).to be_a BigDecimal end end describe('.deprecate') do it "uses ruby warn if active support is not defined" do stub_const("ACTIVE_SUPPORT_DEFINED", false) expect(Kernel).to receive(:warn).once Money.deprecate('ok') end it "uses active support warn if active support is defined" do expect(Kernel).to receive(:warn).never expect_any_instance_of(ActiveSupport::Deprecation).to receive(:warn).once Money.deprecate('ok') end it "only sends a callstack of events outside of the money gem" do expect_any_instance_of(ActiveSupport::Deprecation).to receive(:warn).with( -> (message) { message == "[Shopify/Money] message\n" }, -> (callstack) { !callstack.first.to_s.include?('gems/money') && callstack.size > 0 } ) Money.deprecate('message') end end describe '#use_currency' do it "allows setting the implicit default currency for a block scope" do money = nil Money.with_currency('CAD') do money = Money.new(1.00) end expect(money.currency.iso_code).to eq('CAD') end it "does not use the currency for a block scope when explicitly set" do money = nil Money.with_currency('CAD') do money = Money.new(1.00, 'USD') end expect(money.currency.iso_code).to eq('USD') end context "with .default_currency set" do around(:each) { |test| configure(default_currency: Money::Currency.new('EUR')) { test.run }} it "can be nested and falls back to default_currency outside of the blocks" do money2, money3 = nil money1 = Money.new(1.00) Money.with_currency('CAD') do Money.with_currency('USD') do money2 = Money.new(1.00) end money3 = Money.new(1.00) end money4 = Money.new(1.00) expect(money1.currency.iso_code).to eq('EUR') expect(money2.currency.iso_code).to eq('USD') expect(money3.currency.iso_code).to eq('CAD') expect(money4.currency.iso_code).to eq('EUR') end end end describe '.clamp' do let(:max) { 9000 } let(:min) { -max } it 'returns the same value if the value is within the min..max range' do money = Money.new(5000, 'EUR').clamp(min, max) expect(money.value).to eq(5000) expect(money.currency.iso_code).to eq('EUR') end it 'returns the max value if the original value is larger' do money = Money.new(9001, 'EUR').clamp(min, max) expect(money.clamp(min, max).value).to eq(9000) expect(money.clamp(min, max).currency.iso_code).to eq('EUR') end it 'returns the min value if the original value is smaller' do money = Money.new(-9001, 'EUR').clamp(min, max) expect(money.value).to eq(-9000) expect(money.currency.iso_code).to eq('EUR') end end end
Shopify/money
lib/rubocop/cop/money.rb
<filename>lib/rubocop/cop/money.rb<gh_stars>100-1000 # frozen_string_literal: true require 'rubocop/cop/money/missing_currency' require 'rubocop/cop/money/zero_money'
Shopify/money
lib/money/currency/loader.rb
# frozen_string_literal: true require 'yaml' class Money class Currency module Loader class << self def load_currencies currency_data_path = File.expand_path("../../../../config", __FILE__) currencies = {} currencies.merge! YAML.load_file("#{currency_data_path}/currency_historic.yml") currencies.merge! YAML.load_file("#{currency_data_path}/currency_non_iso.yml") currencies.merge! YAML.load_file("#{currency_data_path}/currency_iso.yml") deep_deduplicate!(currencies) end private def deep_deduplicate!(data) case data when Hash return data if data.frozen? data.transform_keys! { |k| deep_deduplicate!(k) } data.transform_values! { |v| deep_deduplicate!(v) } data.freeze when Array return data if data.frozen? data.map! { |d| deep_deduplicate!(d) }.freeze when String -data else data.freeze end end end end end end
Shopify/money
lib/money/null_currency.rb
<reponame>Shopify/money # frozen_string_literal: true class Money # A placeholder currency for instances where no actual currency is available, # as defined by ISO4217. You should rarely, if ever, need to use this # directly. It's here mostly for backwards compatibility and for that reason # behaves like a dollar, which is how this gem worked before the introduction # of currency. # # Here follows a list of preferred alternatives over using Money with # NullCurrency: # # For comparisons where you don't know the currency beforehand, you can use # Numeric predicate methods like #positive?/#negative?/#zero?/#nonzero?. # Comparison operators with Numeric (==, !=, <=, =>, <, >) work as well. # # @example # Money.new(1, 'CAD').positive? #=> true # Money.new(2, 'CAD') >= 0 #=> true # # Money with NullCurrency has behaviour that may surprise you, such as # database validations or GraphQL enum not allowing the string representation # of NullCurrency. Prefer using Money.new(0, currency) where possible, as # this sidesteps these issues and provides additional currency check # safeties. # # Unlike other currencies, it is allowed to calculate a Money object with # NullCurrency with another currency. The resulting Money object will have # the other currency. # # @example # Money.new(0, Money::NULL_CURRENCY) + Money.new(5, 'CAD') # #=> #<Money value:5.00 currency:CAD> # class NullCurrency attr_reader :iso_code, :iso_numeric, :name, :smallest_denomination, :subunit_symbol, :subunit_to_unit, :minor_units, :symbol, :disambiguate_symbol, :decimal_mark def initialize @symbol = '$' @disambiguate_symbol = nil @subunit_symbol = nil @iso_code = 'XXX' @iso_numeric = '999' @name = 'No Currency' @smallest_denomination = 1 @subunit_to_unit = 100 @minor_units = 2 @decimal_mark = '.' freeze end def compatible?(other) other.is_a?(Currency) || other.is_a?(NullCurrency) end def eql?(other) self.class == other.class && iso_code == other.iso_code end def to_s '' end alias_method :==, :eql? end end
Shopify/money
spec/rubocop/cop/money/zero_money_spec.rb
# frozen_string_literal: true require_relative '../../../rubocop_helper' require 'rubocop/cop/money/zero_money' RSpec.describe RuboCop::Cop::Money::ZeroMoney do subject(:cop) { described_class.new(config) } let(:config) { RuboCop::Config.new } context 'with default configuration' do it 'registers an offense and corrects Money.zero without currency' do expect_offense(<<~RUBY) Money.zero ^^^^^^^^^^ Money.zero is removed, use `Money.new(0, Money::NULL_CURRENCY)`. RUBY expect_correction(<<~RUBY) Money.new(0, Money::NULL_CURRENCY) RUBY end it 'registers an offense and corrects Money.zero with currency' do expect_offense(<<~RUBY) Money.zero('CAD') ^^^^^^^^^^^^^^^^^ Money.zero is removed, use `Money.new(0, 'CAD')`. RUBY expect_correction(<<~RUBY) Money.new(0, 'CAD') RUBY end it 'does not register an offense when using Money.new with a currency' do expect_no_offenses(<<~RUBY) Money.new(0, 'CAD') RUBY end end context 'with ReplacementCurrency configuration' do let(:config) do RuboCop::Config.new( 'Money/ZeroMoney' => { 'ReplacementCurrency' => 'CAD' } ) end it 'registers an offense and corrects Money.zero without currency' do expect_offense(<<~RUBY) Money.zero ^^^^^^^^^^ Money.zero is removed, use `Money.new(0, 'CAD')`. RUBY expect_correction(<<~RUBY) Money.new(0, 'CAD') RUBY end it 'registers an offense and corrects Money.zero with currency' do expect_offense(<<~RUBY) Money.zero('EUR') ^^^^^^^^^^^^^^^^^ Money.zero is removed, use `Money.new(0, 'EUR')`. RUBY expect_correction(<<~RUBY) Money.new(0, 'EUR') RUBY end it 'does not register an offense when using Money.new with a currency' do expect_no_offenses(<<~RUBY) Money.new(0, 'EUR') RUBY end end end
Shopify/money
lib/money/money.rb
<filename>lib/money/money.rb # frozen_string_literal: true require 'forwardable' class Money include Comparable extend Forwardable NULL_CURRENCY = NullCurrency.new.freeze attr_reader :value, :currency def_delegators :@value, :zero?, :nonzero?, :positive?, :negative?, :to_i, :to_f, :hash class << self extend Forwardable attr_accessor :config def_delegators :@config, :parser, :parser=, :default_currency, :default_currency= def configure self.config ||= Config.new yield(config) if block_given? end def new(value = 0, currency = nil) value = Helpers.value_to_decimal(value) currency = Helpers.value_to_currency(currency) if value.zero? @@zero_money ||= {} @@zero_money[currency.iso_code] ||= super(Helpers::DECIMAL_ZERO, currency) else super(value, currency) end end alias_method :from_amount, :new def parse(*args, **kwargs) parser.parse(*args, **kwargs) end def from_subunits(subunits, currency_iso, format: :iso4217) currency = Helpers.value_to_currency(currency_iso) subunit_to_unit_value = if format == :iso4217 currency.subunit_to_unit elsif format == :stripe Helpers::STRIPE_SUBUNIT_OVERRIDE.fetch(currency.iso_code, currency.subunit_to_unit) else raise ArgumentError, "unknown format #{format}" end value = Helpers.value_to_decimal(subunits) / subunit_to_unit_value new(value, currency) end def rational(money1, money2) money1.send(:arithmetic, money2) do factor = money1.currency.subunit_to_unit * money2.currency.subunit_to_unit Rational((money1.value * factor).to_i, (money2.value * factor).to_i) end end def current_currency Thread.current[:money_currency] end def current_currency=(currency) Thread.current[:money_currency] = currency end # Set Money.default_currency inside the supplied block, resets it to # the previous value when done to prevent leaking state. Similar to # I18n.with_locale and ActiveSupport's Time.use_zone. This won't affect # instances being created with explicitly set currency. def with_currency(new_currency) begin old_currency = Money.current_currency Money.current_currency = new_currency yield ensure Money.current_currency = old_currency end end end configure def initialize(value, currency) raise ArgumentError if value.nan? @currency = Helpers.value_to_currency(currency) @value = BigDecimal(value.round(@currency.minor_units)) freeze end def init_with(coder) initialize(Helpers.value_to_decimal(coder['value']), coder['currency']) end def encode_with(coder) coder['value'] = @value.to_s('F') coder['currency'] = @currency.iso_code end def subunits(format: :iso4217) subunit_to_unit_value = if format == :iso4217 @currency.subunit_to_unit elsif format == :stripe Helpers::STRIPE_SUBUNIT_OVERRIDE.fetch(@currency.iso_code, @currency.subunit_to_unit) else raise ArgumentError, "unknown format #{format}" end (@value * subunit_to_unit_value).to_i end def no_currency? currency.is_a?(NullCurrency) end def -@ Money.new(-value, currency) end def <=>(other) return unless other.respond_to?(:to_money) arithmetic(other) do |money| value <=> money.value end end def +(other) arithmetic(other) do |money| return self if money.value == 0 && !no_currency? Money.new(value + money.value, calculated_currency(money.currency)) end end def -(other) arithmetic(other) do |money| return self if money.value == 0 && !no_currency? Money.new(value - money.value, calculated_currency(money.currency)) end end def *(numeric) unless numeric.is_a?(Numeric) if Money.config.legacy_deprecations Money.deprecate("Multiplying Money with #{numeric.class.name} is deprecated and will be removed in the next major release.") else raise ArgumentError, "Money objects can only be multiplied by a Numeric" end end return self if numeric == 1 Money.new(value.to_r * numeric, currency) end def /(numeric) raise "[Money] Dividing money objects can lose pennies. Use #split instead" end def inspect "#<#{self.class} value:#{self} currency:#{self.currency}>" end def ==(other) eql?(other) end # TODO: Remove once cross-currency mathematical operations are no longer allowed def eql?(other) return false unless other.is_a?(Money) return false unless currency.compatible?(other.currency) value == other.value end class ReverseOperationProxy include Comparable def initialize(value) @value = value end def <=>(other) -(other <=> @value) end def +(other) other + @value end def -(other) -(other - @value) end def *(other) other * @value end end def coerce(other) raise TypeError, "Money can't be coerced into #{other.class}" unless other.is_a?(Numeric) [ReverseOperationProxy.new(other), self] end def to_money(curr = nil) if !curr.nil? && no_currency? return Money.new(value, curr) end curr = Helpers.value_to_currency(curr) unless currency.compatible?(curr) msg = "mathematical operation not permitted for Money objects with different currencies #{curr} and #{currency}" if Money.config.legacy_deprecations Money.deprecate("#{msg}. A Money::IncompatibleCurrencyError will raise in the next major release") else raise Money::IncompatibleCurrencyError, msg end end self end def to_d value end def to_formatted_s(style = nil) units = case style when :legacy_dollars 2 when :amount, nil currency.minor_units else raise ArgumentError, "Unexpected format: #{style}" end rounded_value = value.round(units) if units == 0 sprintf("%d", rounded_value) else sign = rounded_value < 0 ? '-' : '' rounded_value = rounded_value.abs sprintf("%s%d.%0#{units}d", sign, rounded_value.truncate, rounded_value.frac * (10 ** units)) end end alias_method :to_s, :to_formatted_s def to_json(options = nil) if (options.is_a?(Hash) && options.delete(:legacy_format)) || Money.config.legacy_json_format to_s else as_json(options).to_json end end def as_json(options = nil) if (options.is_a?(Hash) && options.delete(:legacy_format)) || Money.config.legacy_json_format to_s else { value: to_s(:amount), currency: currency.to_s } end end def abs abs = value.abs return self if value == abs Money.new(abs, currency) end def floor floor = value.floor return self if floor == value Money.new(floor, currency) end def round(ndigits=0) round = value.round(ndigits) return self if round == value Money.new(round, currency) end def fraction(rate) raise ArgumentError, "rate should be positive" if rate < 0 result = value / (1 + rate) Money.new(result, currency) end # @see Money::Allocator#allocate def allocate(splits, strategy = :roundrobin) Money::Allocator.new(self).allocate(splits, strategy) end # @see Money::Allocator#allocate_max_amounts def allocate_max_amounts(maximums) Money::Allocator.new(self).allocate_max_amounts(maximums) end # Split money amongst parties evenly without losing pennies. # # @param [2] number of parties. # # @return [Array<Money, Money, Money>] # # @example # Money.new(100, "USD").split(3) #=> [Money.new(34), Money.new(33), Money.new(33)] def split(num) calculate_splits(num).sum([]) { |value, count| Array.new(count, value) } end # Calculate the splits evenly without losing pennies. # Returns the number of high and low splits and the value of the high and low splits. # Where high represents the Money value with the extra penny # and low a Money without the extra penny. # # @param [2] number of parties. # # @return [Hash<Money, Integer>] # # @example # Money.new(100, "USD").calculate_splits(3) #=> {Money.new(34) => 1, Money.new(33) => 2} def calculate_splits(num) raise ArgumentError, "need at least one party" if num < 1 subunits = self.subunits low = Money.from_subunits(subunits / num, currency) high = Money.from_subunits(low.subunits + 1, currency) num_high = subunits % num {}.tap do |result| result[high] = num_high if num_high > 0 result[low] = num - num_high end end # Clamps the value to be within the specified minimum and maximum. Returns # self if the value is within bounds, otherwise a new Money object with the # closest min or max value. # # @example # Money.new(50, "CAD").clamp(1, 100) #=> Money.new(50, "CAD") # # Money.new(120, "CAD").clamp(0, 100) #=> Money.new(100, "CAD") def clamp(min, max) raise ArgumentError, 'min cannot be greater than max' if min > max clamped_value = min if self.value < min clamped_value = max if self.value > max if clamped_value.nil? self else Money.new(clamped_value, self.currency) end end private def arithmetic(money_or_numeric) raise TypeError, "#{money_or_numeric.class.name} can't be coerced into Money" unless money_or_numeric.respond_to?(:to_money) other = money_or_numeric.to_money(currency) yield(other) end def calculated_currency(other) no_currency? ? other : currency end end
Shopify/money
spec/money_column_spec.rb
<filename>spec/money_column_spec.rb # frozen_string_literal: true require 'spec_helper' class MoneyRecord < ActiveRecord::Base RATE = 1.17 before_validation do self.price_usd = Money.new(self["price"] * RATE, 'USD') if self["price"] end money_column :price, currency_column: 'currency' money_column :prix, currency_column: :devise money_column :price_usd, currency: 'USD' end class MoneyWithValidation < ActiveRecord::Base self.table_name = 'money_records' validates :price, :currency, presence: true money_column :price, currency_column: 'currency' end class MoneyWithReadOnlyCurrency < ActiveRecord::Base self.table_name = 'money_records' money_column :price, currency_column: 'currency', currency_read_only: true end class MoneyRecordCoerceNull < ActiveRecord::Base self.table_name = 'money_records' money_column :price, currency_column: 'currency', coerce_null: true money_column :price_usd, currency: 'USD', coerce_null: true end class MoneyWithDelegatedCurrency < ActiveRecord::Base self.table_name = 'money_records' delegate :currency, to: :delegated_record money_column :price, currency_column: 'currency', currency_read_only: true money_column :prix, currency_column: 'currency2', currency_read_only: true def currency2 delegated_record.currency end private def delegated_record MoneyRecord.new(currency: 'USD') end end class MoneyWithCustomAccessors < ActiveRecord::Base self.table_name = 'money_records' money_column :price, currency_column: 'currency' def price read_money_attribute(:price) end def price=(value) write_money_attribute(:price, value + 1) end end class MoneyClassInheritance < MoneyWithCustomAccessors money_column :prix, currency_column: 'currency' end class MoneyClassInheritance2 < MoneyWithCustomAccessors money_column :price, currency: 'CAD' money_column :price_usd, currency: 'USD' end RSpec.describe 'MoneyColumn' do let(:amount) { 1.23 } let(:currency) { 'EUR' } let(:money) { Money.new(amount, currency) } let(:toonie) { Money.new(2.00, 'CAD') } let(:subject) { MoneyRecord.new(price: money, prix: toonie) } let(:record) do subject.devise = 'CAD' subject.save subject.reload end it 'returns money with currency from the default column' do expect(record.price).to eq(Money.new(1.23, 'EUR')) end it 'writes the currency to the db' do record.update(currency: nil) record.update(price: Money.new(4, 'JPY')) record.reload expect(record.price.value).to eq(4) expect(record.price.currency.to_s).to eq('JPY') end it 'duplicating the record keeps the money values' do expect(MoneyRecord.new(price: money).clone.price).to eq(money) expect(MoneyRecord.new(price: money).dup.price).to eq(money) end it 'returns money with currency from the specified column' do expect(record.prix).to eq(Money.new(2.00, 'CAD')) end it 'returns money with the hardcoded currency' do expect(record.price_usd).to eq(Money.new(1.44, 'USD')) end it 'returns money with null currency when the currency in the DB is invalid' do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once record.update_columns(currency: 'invalid') record.reload expect(record.price.currency).to be_a(Money::NullCurrency) expect(record.price.value).to eq(1.23) end end it 'handles legacy support for saving floats' do record.update(price: 3.21, prix: 3.21) expect(record.price.value).to eq(3.21) expect(record.price.currency.to_s).to eq(currency) expect(record.price_usd.value).to eq(3.76) expect(record.price_usd.currency.to_s).to eq('USD') expect(record.prix.value).to eq(3.21) expect(record.prix.currency.to_s).to eq('CAD') end it 'handles legacy support for saving floats as provided' do record.update(price: 3.2112, prix: 3.2156) expect(record.attributes['price']).to eq(3.2112) expect(record.price.value).to eq(3.21) expect(record.price.currency.to_s).to eq(currency) expect(record.attributes['prix']).to eq(3.2156) expect(record.prix.value).to eq(3.22) expect(record.prix.currency.to_s).to eq('CAD') end it 'handles legacy support for saving string' do record.update(price: '3.21', prix: '3.21') expect(record.price.value).to eq(3.21) expect(record.price.currency.to_s).to eq(currency) expect(record.price_usd.value).to eq(3.76) expect(record.price_usd.currency.to_s).to eq('USD') expect(record.prix.value).to eq(3.21) expect(record.prix.currency.to_s).to eq('CAD') end it 'does not overwrite a currency column with a default currency when saving zero' do expect(record.currency.to_s).to eq('EUR') record.update(price: Money.new(0, Money::NULL_CURRENCY)) expect(record.currency.to_s).to eq('EUR') end it 'does overwrite a currency' do expect(record.currency.to_s).to eq('EUR') record.update(price: Money.new(4, 'JPY')) expect(record.currency.to_s).to eq('JPY') end describe 'non-fractional-currencies' do let(:money) { Money.new(1, 'JPY') } it 'returns money with currency from the default column' do expect(record.price).to eq(Money.new(1, 'JPY')) end end describe 'three-decimal currencies' do let(:money) { Money.new(1.234, 'JOD') } it 'returns money with currency from the default column' do expect(record.price).to eq(Money.new(1.234, 'JOD')) end end describe 'garbage amount' do let(:amount) { 'foo' } it 'raises an ArgumentError' do expect { subject }.to raise_error(ArgumentError) end end describe 'garbage currency' do let(:currency) { 'foo' } it 'raises an UnknownCurrency error' do expect { subject }.to raise_error(Money::Currency::UnknownCurrency) end end describe 'wrong money_column currency arguments' do let(:subject) do class MoneyWithWrongCurrencyArguments < ActiveRecord::Base self.table_name = 'money_records' money_column :price, currency_column: :currency, currency: 'USD' end end it 'raises an ArgumentError' do expect { subject }.to raise_error(ArgumentError, 'cannot set both :currency_column and :currency options') end end describe 'missing money_column currency arguments' do let(:subject) do class MoneyWithWrongCurrencyArguments < ActiveRecord::Base self.table_name = 'money_records' money_column :price end end it 'raises an ArgumentError' do expect { subject }.to raise_error(ArgumentError, 'must set one of :currency_column or :currency options') end end describe 'null currency and validations' do let(:currency) { Money::NULL_CURRENCY } let(:subject) { MoneyWithValidation.new(price: money) } it 'is not allowed to be saved because `to_s` returns a blank string' do subject.valid? expect(subject.errors[:currency]).to include("can't be blank") end end describe 'read_only_currency true' do it 'does not write the currency to the db' do record = MoneyWithReadOnlyCurrency.create record.update_columns(currency: 'USD') expect { record.update(price: Money.new(4, 'CAD')) }.to raise_error(MoneyColumn::CurrencyReadOnlyError) end it 'legacy_deprecations does not write the currency to the db' do configure(legacy_deprecations: true) do record = MoneyWithReadOnlyCurrency.create record.update_columns(currency: 'USD') expect(Money).to receive(:deprecate).once record.update(price: Money.new(4, 'CAD')) expect(record.price.value).to eq(4) expect(record.price.currency.to_s).to eq('USD') end end it 'reads the currency that is already in the db' do record = MoneyWithReadOnlyCurrency.create record.update_columns(currency: 'USD', price: 1) record.reload expect(record.price.value).to eq(1) expect(record.price.currency.to_s).to eq('USD') end it 'reads an invalid currency from the db and generates a no currency object' do configure(legacy_deprecations: true) do expect(Money).to receive(:deprecate).once record = MoneyWithReadOnlyCurrency.create record.update_columns(currency: 'invalid', price: 1) record.reload expect(record.price.value).to eq(1) expect(record.price.currency.to_s).to eq('') end end it 'sets the currency correctly when the currency is changed' do record = MoneyWithReadOnlyCurrency.create(currency: 'CAD', price: 1) record.currency = 'USD' expect(record.price.currency.to_s).to eq('USD') end it 'handle cases where the delegate allow_nil is false' do record = MoneyWithDelegatedCurrency.new(price: Money.new(10, 'USD')) expect(record.price.currency.to_s).to eq('USD') end it 'handle cases where a manual delegate does not allow nil' do record = MoneyWithDelegatedCurrency.new(prix: Money.new(10, 'USD')) expect(record.price.currency.to_s).to eq('USD') end end describe 'coerce_null' do it 'returns nil when money value have not been set and coerce_null is false' do record = MoneyRecord.new(price: nil) expect(record.price).to eq(nil) expect(record.price_usd).to eq(nil) end it 'returns 0$ when money value have not been set and coerce_null is true' do record = MoneyRecordCoerceNull.new(price: nil) expect(record.price.value).to eq(0) expect(record.price_usd.value).to eq(0) end end describe 'memoization' do it 'correctly memoizes the read value' do expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(nil) price = Money.new(1, 'USD') record = MoneyRecord.new(price: price) expect(record.price).to eq(price) expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(price) end it 'memoizes values get reset when writing a new value' do price = Money.new(1, 'USD') record = MoneyRecord.new(price: price) expect(record.price).to eq(price) price = Money.new(2, 'USD') record.update!(price: price) expect(record.price).to eq(price) expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(price) end it 'reload will clear memoized money values' do price = Money.new(1, 'USD') record = MoneyRecord.create(price: price) expect(record.price).to eq(price) expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(price) record.reload expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(nil) record.price expect(record.instance_variable_get(:@money_column_cache)["price"]).to eq(price) end it 'reload will clear record cache' do price = Money.new(1, 'USD') price2 = Money.new(2, 'USD') record = MoneyRecord.create(price: price) expect(record.price).to eq(price) expect(record[:price]).to eq(price) ActiveRecord::Base.connection.execute("UPDATE money_records SET price=#{price2.value} WHERE id=#{record.id}") expect(record[:price]).to_not eq(price2) expect(record.price).to_not eq(price2) record.reload expect(record[:price]).to eq(price2) expect(record.price).to eq(price2) end end describe 'ActiveRecord querying' do it 'can be serialized for querying on the value' do price = Money.new(1, 'USD') record = MoneyRecord.create!(price: price) expect(MoneyRecord.find_by(price: price)).to eq(record) end it 'nil value persist in the DB' do record = MoneyRecord.create!(price: nil) expect(MoneyRecord.find_by(price: nil)).to eq(record) end end describe 'money column attribute accessors' do it 'allows to overwrite the setter' do amount = Money.new(1, 'USD') expect(MoneyWithCustomAccessors.new(price: amount).price).to eq(MoneyRecord.new(price: amount).price + 1) end it 'correctly assigns the money_column_cache' do amount = Money.new(1, 'USD') object = MoneyWithCustomAccessors.new(price: amount) expect(object.instance_variable_get(:@money_column_cache)['price']).to eql(nil) expect(object.price).to eql(amount + 1) expect(object.instance_variable_get(:@money_column_cache)['price']).to eql(amount + 1) end end describe 'class inheritance' do it 'shares money columns declared on the parent class' do expect(MoneyClassInheritance.instance_variable_get(:@money_column_options).dig('price', :currency_column)).to eq('currency') expect(MoneyClassInheritance.instance_variable_get(:@money_column_options).dig('price', :currency)).to eq(nil) expect(MoneyClassInheritance.new(price: Money.new(1, 'USD')).price).to eq(Money.new(2, 'USD')) end it 'subclass can define extra money columns' do expect(MoneyClassInheritance.instance_variable_get(:@money_column_options).keys).to include('prix') expect(MoneyClassInheritance.instance_variable_get(:@money_column_options).keys).to_not include('price_usd') expect(MoneyClassInheritance.new(prix: Money.new(1, 'USD')).prix).to eq(Money.new(1, 'USD')) end it 'subclass can redefine money columns from parent' do expect(MoneyClassInheritance2.instance_variable_get(:@money_column_options).dig('price', :currency)).to eq('CAD') expect(MoneyClassInheritance2.instance_variable_get(:@money_column_options).dig('price', :currency_column)).to eq(nil) expect(MoneyClassInheritance2.instance_variable_get(:@money_column_options).keys).to_not include('prix') end end describe 'default_currency = nil' do around do |example| configure(default_currency: nil) { example.run } end it 'writes currency from input value to the db' do record.update(currency: nil) record.update(price: Money.new(7, 'GBP')) record.reload expect(record.price.value).to eq(7) expect(record.price.currency.to_s).to eq('GBP') end it 'raises missing currency error reading a value that was saved using legacy non-money object' do record.update(currency: nil, price: 3) expect { record.price }.to raise_error(ArgumentError, 'missing currency') end it 'handles legacy support for saving price and currency separately' do record.update(currency: nil) record.update(price: 7, currency: 'GBP') record.reload expect(record.price.value).to eq(7) expect(record.price.currency.to_s).to eq('GBP') end end end
Shopify/money
spec/allocator_spec.rb
# frozen_string_literal: true require 'spec_helper' RSpec.describe "Allocator" do describe "allocate"do specify "#allocate takes no action when one gets all" do expect(new_allocator(5).allocate([1])).to eq([Money.new(5)]) end specify "#allocate does not lose pennies" do moneys = new_allocator(0.05).allocate([0.3,0.7]) expect(moneys[0]).to eq(Money.new(0.02)) expect(moneys[1]).to eq(Money.new(0.03)) end specify "#allocate does not lose dollars with non-decimal currency" do moneys = new_allocator(5, 'JPY').allocate([0.3,0.7]) expect(moneys[0]).to eq(Money.new(2, 'JPY')) expect(moneys[1]).to eq(Money.new(3, 'JPY')) end specify "#allocate does not lose dollars with three decimal currency" do moneys = new_allocator(0.005, 'JOD').allocate([0.3,0.7]) expect(moneys[0]).to eq(Money.new(0.002, 'JOD')) expect(moneys[1]).to eq(Money.new(0.003, 'JOD')) end specify "#allocate does not lose pennies even when given a lossy split" do moneys = new_allocator(1).allocate([0.333,0.333, 0.333]) expect(moneys[0].subunits).to eq(34) expect(moneys[1].subunits).to eq(33) expect(moneys[2].subunits).to eq(33) end specify "#allocate requires total to be less than 1" do expect { new_allocator(0.05).allocate([0.5,0.6]) }.to raise_error(ArgumentError) end specify "#allocate will use rationals if provided" do splits = [128400,20439,14589,14589,25936].map{ |num| Rational(num, 203953) } # sums to > 1 if converted to float expect(new_allocator(2.25).allocate(splits)).to eq([Money.new(1.42), Money.new(0.23), Money.new(0.16), Money.new(0.16), Money.new(0.28)]) end specify "#allocate will convert rationals with high precision" do ratios = [Rational(1, 1), Rational(0)] expect(new_allocator("858993456.12").allocate(ratios)).to eq([Money.new("858993456.12"), Money.new(0, Money::NULL_CURRENCY)]) ratios = [Rational(1, 6), Rational(5, 6)] expect(new_allocator("3.00").allocate(ratios)).to eq([Money.new("0.50"), Money.new("2.50")]) end specify "#allocate doesn't raise with weird negative rational ratios" do rate = Rational(-5, 1201) expect { new_allocator(1).allocate([rate, 1 - rate]) }.not_to raise_error end specify "#allocate fills pennies from beginning to end with roundrobin strategy" do moneys = new_allocator(0.05).allocate([0.3,0.7], :roundrobin) expect(moneys[0]).to eq(Money.new(0.02)) expect(moneys[1]).to eq(Money.new(0.03)) end specify "#allocate fills pennies from end to beginning with roundrobin_reverse strategy" do moneys = new_allocator(0.05).allocate([0.3,0.7], :roundrobin_reverse) expect(moneys[0]).to eq(Money.new(0.01)) expect(moneys[1]).to eq(Money.new(0.04)) end specify "#allocate raise ArgumentError when invalid strategy is provided" do expect { new_allocator(0.03).allocate([0.5, 0.5], :bad_strategy_name) }.to raise_error(ArgumentError, "Invalid strategy. Valid options: :roundrobin, :roundrobin_reverse") end specify "#allocate does not raise ArgumentError when invalid splits types are provided" do moneys = new_allocator(0.03).allocate([0.5, 0.5], :roundrobin) expect(moneys[0]).to eq(Money.new(0.02)) expect(moneys[1]).to eq(Money.new(0.01)) end end describe 'allocate_max_amounts' do specify "#allocate_max_amounts returns the weighted allocation without exceeding the maxima when there is room for the remainder" do expect( new_allocator(30.75).allocate_max_amounts([Money.new(26), Money.new(4.75)]), ).to eq([Money.new(26), Money.new(4.75)]) end specify "#allocate_max_amounts returns the weighted allocation without exceeding the maxima when there is room for the remainder with currency" do expect( new_allocator(3075, 'JPY').allocate_max_amounts([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]), ).to eq([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]) end specify "#allocate_max_amounts legal computation with no currency objects" do expect( new_allocator(3075, 'JPY').allocate_max_amounts([2600, 475]), ).to eq([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]) expect( new_allocator(3075, Money::NULL_CURRENCY).allocate_max_amounts([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]), ).to eq([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]) end specify "#allocate_max_amounts illegal computation across currencies" do expect { new_allocator(3075, 'USD').allocate_max_amounts([Money.new(2600, 'JPY'), Money.new(475, 'JPY')]) }.to raise_error(ArgumentError) end specify "#allocate_max_amounts drops the remainder when returning the weighted allocation without exceeding the maxima when there is no room for the remainder" do expect( new_allocator(30.75).allocate_max_amounts([Money.new(26), Money.new(4.74)]), ).to eq([Money.new(26), Money.new(4.74)]) end specify "#allocate_max_amounts returns the weighted allocation when there is no remainder" do expect( new_allocator(30).allocate_max_amounts([Money.new(15), Money.new(15)]), ).to eq([Money.new(15), Money.new(15)]) end specify "#allocate_max_amounts allocates the remainder round-robin when the maxima are not reached" do expect( new_allocator(1).allocate_max_amounts([Money.new(33), Money.new(33), Money.new(33)]), ).to eq([Money.new(0.34), Money.new(0.33), Money.new(0.33)]) end specify "#allocate_max_amounts allocates up to the maxima specified" do expect( new_allocator(100).allocate_max_amounts([Money.new(5), Money.new(2)]), ).to eq([Money.new(5), Money.new(2)]) end specify "#allocate_max_amounts supports all-zero maxima" do expect( new_allocator(3).allocate_max_amounts([Money.new(0, Money::NULL_CURRENCY), Money.new(0, Money::NULL_CURRENCY), Money.new(0, Money::NULL_CURRENCY)]), ).to eq([Money.new(0, Money::NULL_CURRENCY), Money.new(0, Money::NULL_CURRENCY), Money.new(0, Money::NULL_CURRENCY)]) end specify "#allocate_max_amounts allocates the right amount without rounding error" do expect( new_allocator(24.2).allocate_max_amounts([Money.new(46), Money.new(46), Money.new(50), Money.new(50),Money.new(50)]), ).to eq([Money.new(4.6), Money.new(4.6), Money.new(5), Money.new(5), Money.new(5)]) end end def new_allocator(amount, currency = nil) Money::Allocator.new(Money.new(amount, currency)) end end
Shopify/money
lib/rubocop/cop/money/zero_money.rb
<reponame>Shopify/money # frozen_string_literal: true module RuboCop module Cop module Money class ZeroMoney < Cop # `Money.zero` and it's alias `empty`, with or without currency # argument is removed in favour of the more explicit Money.new # syntax. Supplying it with a real currency is preferred for # additional currency safety checks. # # If no currency was supplied, it defaults to # Money::NULL_CURRENCY which was the default setting of # Money.default_currency and should effectively be the same. The cop # can be configured with a ReplacementCurrency in case that is more # appropriate for your application. # # @example # # # bad # Money.zero # # # good when configured with `ReplacementCurrency: CAD` # Money.new(0, 'CAD') # MSG = 'Money.zero is removed, use `Money.new(0, %<currency>s)`.' def_node_matcher :money_zero, <<~PATTERN (send (const {nil? cbase} :Money) {:zero :empty} $...) PATTERN def on_send(node) money_zero(node) do |currency_arg| add_offense(node, message: format(MSG, currency: replacement_currency(currency_arg))) end end def autocorrect(node) receiver, _ = *node lambda do |corrector| money_zero(node) do |currency_arg| replacement_currency = replacement_currency(currency_arg) corrector.replace( node.loc.expression, "#{receiver.source}.new(0, #{replacement_currency})" ) end end end private def replacement_currency(currency_arg) return currency_arg.first.source unless currency_arg.empty? return "'#{cop_config['ReplacementCurrency']}'" if cop_config['ReplacementCurrency'] 'Money::NULL_CURRENCY' end end end end end
Shopify/money
spec/rails_spec_helper.rb
# frozen_string_literal: true require "active_job" require_relative "spec_helper" Money::Railtie.initializers.each(&:run) class MoneyTestJob < ActiveJob::Base def perform(_params) end end
Shopify/money
lib/money/railtie.rb
# frozen_string_literal: true class Money class Railtie < Rails::Railtie initializer "shopify-money.setup_active_job_serializer" do ActiveSupport.on_load :active_job do require_relative "rails/job_argument_serializer" ActiveJob::Serializers.add_serializers ::Money::Rails::JobArgumentSerializer end end end end
arca0/bulmatown
lib/bulmatown/version.rb
<reponame>arca0/bulmatown<filename>lib/bulmatown/version.rb # frozen_string_literal: true module Bulmatown VERSION = "1.0.7" end
arca0/bulmatown
bridgetown.automation.rb
<reponame>arca0/bulmatown<filename>bridgetown.automation.rb # Thanks to https://github.com/ParamagicDev for a bunch of the smarts in this # automation :) add_bridgetown_plugin "bulmatown" add_bridgetown_plugin "bridgetown-quick-search" # 0.15 bug! :( can't use this: #add_yarn_for_gem "bulmatown" gem_version = (`bundle info bulmatown`).match(/\*.*\((.*?)\)/)[1] run "yarn add bulmatown@#{gem_version}" require 'fileutils' require 'shellwords' unless Dir.exist? "frontend/fonts" FileUtils.mkdir_p "frontend/fonts" end run "cp node_modules/fork-awesome/fonts/* frontend/fonts" javascript_import 'import Bulmatown from "bulmatown"' # *** Set up remote repo pull # Dynamically determined due to having to load from the tempdir @current_dir = File.expand_path(__dir__) # If its a remote file, the branch is appended to the end, so go up a level ROOT_PATH = if __FILE__ =~ %r{\Ahttps?://} File.expand_path('../', __dir__) else File.expand_path(__dir__) end DIR_NAME = File.basename(ROOT_PATH) # DIR_NAME = 'bulmtatown' GITHUB_PATH = "https://github.com/arca0/#{DIR_NAME}.git" # Copied from: https://github.com/mattbrictson/rails-template # Add this template directory to source_paths so that Thor actions like # copy_file and template resolve against our source files. If this file was # invoked remotely via HTTP, that means the files are not present locally. # In that case, use `git clone` to download them to a local temporary dir. def add_template_repository_to_source_path if __FILE__ =~ %r{\Ahttps?://} require 'tmpdir' source_paths.unshift(tempdir = Dir.mktmpdir(DIR_NAME + '-')) at_exit { FileUtils.remove_entry(tempdir) } run("git clone --quiet #{GITHUB_PATH.shellescape} #{tempdir.shellescape}") if (branch = __FILE__[%r{#{DIR_NAME}/(.+)/bridgetown.automation.rb}, 1]) Dir.chdir(tempdir) { system("git checkout #{branch}") } @current_dir = File.expand_path(tempdir) end else source_paths.unshift(DIR_NAME) end end def copy_if_exists(file) target = File.exist?("src/_layouts/#{file}.html") ? "src/_layouts/#{file}.html" : "src/_layouts/#{file}.liquid" copy_file "example/src/_layouts/#{file}.liquid", target end def substitute_in_default_if_exists if File.exists?("src/_layouts/default.liquid") gsub_file "src/_layouts/default.liquid", '{% render "footer", ', '{% render "footer", url: site.url, ' elsif File.exists?("src/_layouts/default.html") gsub_file "src/_layouts/default.html", '{% render "footer", ', '{% render "footer", url: site.url, ' else say_status :bulmatown, "Could not find the default template. You will have to add the url parameter to the render command manually" end end if yes? "The Bulmatown installer can update styles, layouts, and page templates to use the new theme. You'll have the option to type 'a' to overwrite all existing files or 'd' to inspect each change. Would you like to proceed? (Y/N)" add_template_repository_to_source_path create_file "frontend/styles/index.scss", '@import "~bulmatown/frontend/styles"' ["home", "page", "post"].each { |f| copy_if_exists(f) } substitute_in_default_if_exists copy_file "example/src/index.md", "src/index.md" copy_file "example/src/posts.md", "src/posts.md" copy_file "example/src/404.html", "src/404.html" copy_file "example/src/_components/navbar.liquid", "src/_components/navbar.liquid" copy_file "example/src/_components/footer.liquid", "src/_components/footer.liquid" inject_into_file "bridgetown.config.yml", "pagination:\n enabled: true\n", after: "permalink: pretty\n" end twitter = ask "Do you have a Twitter handle? If so, enter it here, otherwise type 'no'" if twitter != "" && twitter != "no" append_to_file "src/_data/site_metadata.yml" do <<~YAML twitter: #{twitter} YAML end end say_status :bulmatown, "Theme installation complete! Enjoy your fresh new design :)"
gildas/fluent-plugin-bunyan
lib/fluent/plugin/parser_bunyan.rb
<reponame>gildas/fluent-plugin-bunyan<gh_stars>0 # # Copyright 2020- <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "fluent/parser" module Fluent module Plugin class BunyanParser < JSONParser Fluent::Plugin.register_parser("bunyan", self) def configure(conf) conf["time_format"] = "%iso8601" super(conf) end def parse(text) # Example of a log line from containerd we want to get stuff from: # 2020-03-16T22:14:05.710251038+09:00 stdout F {"UserAgent":"kube-probe/1.17","hostname":"helloworld-go-helloworld-5649dfd7bd-k8954","level":30,"msg":"request start: GET /","name":"helloworld","pid":1,"remote":"10.1.10.1:60114","reqid":"e4745ed6-82d4-4013-aeda-1d02bef42331","scope":"/","tid":17,"time":"2020-03-16T13:14:05Z","topic":"route","v":0} # Example of a log line from docker for mac we want to get stuff from: # {"log":"{\"UserAgent\":\"HTTPie/2.0.0\",\"hostname\":\"helloworld-859745b47d-5dlbn\",\"level\":30,\"msg\":\"request start: GET /\",\"name\":\"helloworld\",\"pid\":1,\"remote\":\"192.168.65.3:42018\",\"reqid\":\"ba054f49-d97e-4970-89c4-dd3b75270e6a\",\"scope\":\"/\",\"tid\":14,\"time\":\"2020-03-24T08:29:02Z\",\"topic\":\"route\",\"v\":0}\n","stream":"stdout","time":"2020-03-24T08:29:02.3995324Z"} if text =~ /[^{]*({.*)/ super(text.sub(/[^{]*({.*)/, '\1')) do |time, record| if record then if record["log"] then # This is a Docker style log message begin r = JSON.load(record["log"]) r.delete("time") record.merge!(r) record.delete("log") rescue JSON::ParserError end end record["severity"] = severity(record["level"] || 0) record["host"] = record.delete("hostname") record["message"] = record.delete("msg") record.delete("v") end yield time, record end end end def severity(level) return "fatal" if level >= 60 return "error" if level >= 50 return "warn" if level >= 40 return "info" if level >= 30 return "debug" if level >= 20 return "trace" end def version return "0.0.5" end end end end
gildas/fluent-plugin-bunyan
fluent-plugin-bunyan.gemspec
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "fluent-plugin-bunyan" #spec.version = Fluent::Plugin::BunyanParser.new.version spec.version = "0.0.5" spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Fluentd Parser for applications that produce [Bunyan](https://github.com/trentm/node-bunyan) logs.} spec.description = spec.summary spec.homepage = "https://github.com/gildas/fluent-plugin-bunyan" spec.license = "MIT" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage spec.metadata["changelog_uri"] = "https://github.com/gildas/fluent-plugin-bunyan/blob/master/CHANGELOG.md" test_files, files = `git ls-files -z`.split("\x0").partition do |f| f.match(%r{^(test|spec|features)/}) end spec.files = files spec.executables = files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = test_files spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.14" spec.add_development_dependency "test-unit", "~> 3.0" spec.add_runtime_dependency "fluentd", [">= 0.14.10", "< 2"] end
gildas/fluent-plugin-bunyan
test/plugin/test_parser_bunyan.rb
require "helper" require "fluent/plugin/parser_bunyan.rb" class BunyanParserTest < Test::Unit::TestCase setup do Fluent::Test.setup end CONFIG = %[ pattern apache ] sub_test_case "parse" do test "can parse simple entry" do driver = create_driver(CONFIG) text = '{"hostname":"helloworld-go-helloworld-5649dfd7bd-k8954","level":30,"msg":"The message","name":"helloworld","pid":1,"scope":"main","tid":1,"time":"2020-03-10T07:08:41Z","topic":"main","v":0}' expected_time = Time.utc(2020, 3, 10, 7, 8, 41).to_i expected_record = { "host" => "helloworld-go-helloworld-5649dfd7bd-k8954", "name" => "helloworld", "severity" => "info", "level" => 30, "message" => "The message", "topic" => "main", "scope" => "main", "pid" => 1, "tid" => 1, } driver.instance.parse(text) do |time, record| assert_equal(expected_record, record) assert_equal(expected_time, time) end end test "can parse entry with custom properties" do driver = create_driver(CONFIG) text = '{"hostname":"helloworld-go-helloworld-5649dfd7bd-k8954","level":50,"msg":"Failed to be happy","name":"helloworld","pid":1,"reqid":"0ba850ff-1e1f-4bcf-8288-135927bb850f","scope":"start","tid":21,"time":"2020-03-10T15:04:19Z","topic":"server","v":0}' expected_time = Time.utc(2020, 3, 10, 15, 4, 19).to_i expected_record = { "host" => "helloworld-go-helloworld-5649dfd7bd-k8954", "name" => "helloworld", "severity" => "error", "level" => 50, "message" => "Failed to be happy", "topic" => "server", "scope" => "start", "pid" => 1, "tid" => 21, "reqid" => "0ba850ff-1e1f-4bcf-8288-135927bb850f", } driver.instance.parse(text) do |time, record| assert_equal(expected_record, record) assert_equal(expected_time, time) end end test "can parse entry with complex custom properties" do driver = create_driver(CONFIG) text = '{"hostname":"helloworld-go-helloworld-5649dfd7bd-k8954","level":50,"msg":"Failed to be happy","name":"helloworld","pid":1,"err":{"text": "aouch", "code": 404},"reqid":"0ba850ff-1e1f-4bcf-8288-135927bb850f","scope":"start","tid":21,"time":"2020-03-10T15:04:19Z","topic":"server","v":0}' expected_time = Time.utc(2020, 3, 10, 15, 4, 19).to_i expected_record = { "host" => "helloworld-go-helloworld-5649dfd7bd-k8954", "name" => "helloworld", "severity" => "error", "level" => 50, "message" => "Failed to be happy", "topic" => "server", "scope" => "start", "pid" => 1, "tid" => 21, "reqid" => "0ba850ff-1e1f-4bcf-8288-135927bb850f", "err" => { "code" => 404, "text" => "aouch", }, } driver.instance.parse(text) do |time, record| assert_equal(expected_record, record) assert_equal(expected_time, time) end end end test "can parse entry from containerd" do driver = create_driver(CONFIG) text = '2020-03-10T07:08:41.710251038+09:00 stdout F {"hostname":"helloworld-go-helloworld-5649dfd7bd-k8954","level":30,"msg":"The message","name":"helloworld","pid":1,"scope":"main","tid":1,"time":"2020-03-10T07:08:41Z","topic":"main","v":0}' expected_time = Time.utc(2020, 3, 10, 7, 8, 41).to_i expected_record = { "host" => "helloworld-go-helloworld-5649dfd7bd-k8954", "name" => "helloworld", "severity" => "info", "level" => 30, "message" => "The message", "topic" => "main", "scope" => "main", "pid" => 1, "tid" => 1, } driver.instance.parse(text) do |time, record| assert_equal(expected_record, record) assert_equal(expected_time, time) end end test "can parse entry from Docker for Mac/Windows" do driver = create_driver(CONFIG) text = '{"log":"{\"hostname\":\"helloworld-859745b47d-5dlbn\",\"level\":30,\"msg\":\"The message\",\"name\":\"helloworld\",\"pid\":1,\"remote\":\"192.168.65.3:42018\",\"scope\":\"main\",\"tid\":14,\"time\":\"2020-03-24T08:29:02Z\",\"topic\":\"main\",\"v\":0}\n","stream":"stdout","time":"2020-03-24T08:29:02.3995324Z"}' expected_time = Time.utc(2020, 3, 24, 8, 29, 2).to_i expected_record = { "host" => "helloworld-859745b47d-5dlbn", "name" => "helloworld", "severity" => "info", "level" => 30, "message" => "The message", "remote" => "192.168.65.3:42018", "topic" => "main", "scope" => "main", "stream" => "stdout", "pid" => 1, "tid" => 14, } driver.instance.parse(text) do |time, record| assert_equal(expected_record, record) assert_equal(expected_time, time) end end private def create_driver(conf = CONFIG) Fluent::Test::Driver::Parser.new(Fluent::Plugin::BunyanParser).configure(conf) end end
concord-consortium/secure-samesite-cookies
lib/rack/secure_samesite_cookies/version.rb
<filename>lib/rack/secure_samesite_cookies/version.rb module Rack class SecureSamesiteCookies VERSION = "1.0.2" end end
concord-consortium/secure-samesite-cookies
spec/lib/rack/secure_samesite_cookies_spec.rb
require_relative "../../spec_helper" def cookie_from_response(response=last_response) Hash[response.header["Set-Cookie"].lines.map { |line| cookie = Rack::Test::Cookie.new(line.chomp) [cookie.name, line.chomp] }]["foo"] end describe "Rack::SecureSiteSiteCookies" do include Rack::Test::Methods let(:raw_cookie) { "foo=bar" } let(:non_chrome_ua) { "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" } let(:chrome_66_and_lower_ua) { "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36" } let(:chrome_67_and_above_ua) { "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3945.130 Safari/537.36" } let(:app) do dummy_app = ->(env) { [200, {"Set-Cookie" => raw_cookie}, "Hello World"] } Rack::SecureSiteSiteCookies.new(dummy_app) end describe "with non-ssl requests and non-chrome user-agents" do it "doesn't add secure or samesite attributes" do header "User-Agent", non_chrome_ua get "/" assert_equal cookie_from_response(), raw_cookie end end describe "with ssl requests and non-chrome user-agents" do it "adds secure attribute but not samesite attribute" do header "User-Agent", non_chrome_ua get "/", {}, {'HTTPS' => 'on'} assert_equal cookie_from_response(), "#{raw_cookie}; secure" end end describe "with non-ssl requests and chrome <= 66 user-agents" do it "does not add secure attribute or samesite attribute" do header "User-Agent", chrome_66_and_lower_ua get "/" assert_equal cookie_from_response(), raw_cookie end end describe "with ssl requests and chrome <= 66 user-agents" do it "adds secure attribute but not samesite attribute" do header "User-Agent", chrome_66_and_lower_ua get "/", {}, {'HTTPS' => 'on'} assert_equal cookie_from_response(), "#{raw_cookie}; secure" end end describe "with non-ssl requests and chrome > 66 user-agents" do it "does not add secure attribute or samesite attribute" do header "User-Agent", chrome_67_and_above_ua get "/" assert_equal cookie_from_response(), raw_cookie end end describe "with ssl requests and chrome > 66 user-agents" do it "adds secure attribute and samesite attribute" do header "User-Agent", chrome_67_and_above_ua get "/", {}, {'HTTPS' => 'on'} assert_equal cookie_from_response(), "#{raw_cookie}; secure; SameSite=None" end end end
concord-consortium/secure-samesite-cookies
lib/rack/secure_samesite_cookies/railtie.rb
<reponame>concord-consortium/secure-samesite-cookies module Rack class SecureSamesiteCookies class Railtie < ::Rails::Railtie initializer "rack-secure_samesite_cookies.configure_rails_initialization" do |app| app.config.middleware.insert_after(Rack::Runtime, Rack::SecureSiteSiteCookies) end end end end
concord-consortium/secure-samesite-cookies
lib/rack/secure_samesite_cookies.rb
require "rack/secure_samesite_cookies/version" require 'rack/secure_samesite_cookies/railtie' if defined?(Rails::Railtie) module Rack class SecureSiteSiteCookies COOKIE_SEPARATOR = "\n".freeze def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) if headers.key?('Set-Cookie') cookies = headers['Set-Cookie'].split(COOKIE_SEPARATOR) # set secure flag if this is https request add_secure = Rack::Request.new(env).ssl? # add SiteSite attribute only for Chrome 67+ for now when in secure mode # note: Chrome user-agents look like this: ... Chrome/66.0.3359.139 ... chrome_match = (env["HTTP_USER_AGENT"] || "").match(/\s(chrome)\/(?<version>\d+)/i) is_chrome_67_or_greater = !!chrome_match && (chrome_match[:version].to_i >= 67) add_same_site = add_secure && is_chrome_67_or_greater cookies.each do |cookie| # can't use .present? as we aren't running in rails in tests next if cookie.empty? || (cookie.gsub(/\s/, "").length == 0) if add_secure && cookie !~ /;\s*secure/i cookie << '; secure' end if add_same_site && cookie !~ /;\ssamesite/i cookie << '; SameSite=None' end end headers['Set-Cookie'] = cookies.join(COOKIE_SEPARATOR) end [status, headers, body] end end end
concord-consortium/secure-samesite-cookies
spec/spec_helper.rb
require "minitest/spec" require "minitest/autorun" require "rack/test" require "rack/secure_samesite_cookies"
sharex-admin/token-profile
format.rb
require "eth" require "json" workdir = Dir.pwd Dir.each_child("erc20") do |file| next if file == "$template.json" || !file.end_with?("json") puts "processing file:#{file}" fullpath = "#{workdir}/erc20/#{file}" begin json = JSON.parse IO.read(fullpath) rescue => e puts e.message exit false end address_text = json["address"] downcase_address = address_text.downcase checksum_address = Eth::Utils.format_address address_text if address_text != checksum_address puts "rewrite file:#{file}" json["address"] = checksum_address File.open(fullpath, 'w') {|f| f.write JSON.pretty_generate(json, indent: " "*4) } end img = "#{workdir}/images/#{downcase_address}.png" if File.exists?(img) puts "rewrite image:#{file}" File.rename(img, "#{workdir}/images/#{checksum_address}.png") end end
PikachuEXE/memcached_cloud_gem
spec/spec_helper.rb
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'rubygems' require 'bundler' Bundler.setup :default, :test
PikachuEXE/memcached_cloud_gem
memcached_cloud.gemspec
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "memcached_cloud/version" Gem::Specification.new do |spec| spec.name = "memcached_cloud" spec.version = MemcachedCloud::VERSION spec.summary = "Compatibility gem for using memcached libraries with Memcached Cloud" spec.description = "Simple gem that sets the memcached environment variables to the values of corresponding Memcached Cloud environment variables. This makes it seemless to use Memcached Cloud in environments like Heroku using the Dalli or other compatible memcached gem." spec.authors = ["PikachuEXE"] spec.email = "<EMAIL>" spec.homepage = "http://github.com/PikachuEXE/memcached_cloud" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.5" spec.add_development_dependency "rake", "~> 10.1" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "gem-release", ">= 0.7" end
PikachuEXE/memcached_cloud_gem
lib/memcached_cloud.rb
<gh_stars>0 require 'memcached_cloud/version' module MemcachedCloud extend self def setup { "MEMCACHEDCLOUD_SERVERS" => "MEMCACHE_SERVERS", "MEMCACHEDCLOUD_USERNAME" => "MEMCACHE_USERNAME", "MEMCACHEDCLOUD_PASSWORD" => "<PASSWORD>", }.each do |key, value| ENV[value] = ENV[key] if ENV[key] end end end MemcachedCloud.setup