repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
unindented/unindented-rails
spec/routing/tags_routing_spec.rb
describe TagsController do describe 'routing' do it 'routes `/tags` to #index' do expect(get '/tags/').to route_to('tags#index') end it 'routes `/tags/foobar` to #show' do expect(get '/tags/foobar/').to route_to('tags#show', locator: 'foobar') end end describe 'named routes' do it 'routes `tags_path` to #index' do expect(get tags_path).to route_to('tags#index') end it 'routes `tag_path(:locator)` to #show' do expect(get tag_path('foobar')).to route_to('tags#show', locator: 'foobar') end end end
unindented/unindented-rails
app/controllers/contents_controller.rb
class ContentsController < ApplicationController skip_before_action :verify_authenticity_token def show locator = params[:locator] filename = params[:filename] if filename.present? render_file(locator, filename) else render_content(locator) end end private def render_file(locator, filename) @content = Content .find_by!(locator: locator) .decorate ext = File.extname(filename).downcase.tr('.', '') type = Mime::Type.lookup_by_extension(ext) path = File.expand_path(File.join([Rails.root, 'contents', @content.path, filename])) send_data File.read(path), type: type, disposition: :inline end def render_content(locator) @content = Content .find_by!(locator: locator) .decorate render text: @content.body_html, layout: @content.category end end
unindented/unindented-rails
spec/routing/errors_routing_spec.rb
<filename>spec/routing/errors_routing_spec.rb describe ErrorsController do describe 'routing' do it 'routes `/errors/404` to #show' do expect(get '/errors/404/').to route_to( 'errors#show', error: '404') end it 'routes `/errors/500` to #show' do expect(get '/errors/500/').to route_to( 'errors#show', error: '500') end end describe 'named routes' do it 'routes `error_path(:error) to #show`' do expect(get error_path('404')).to route_to( 'errors#show', error: '404') end it 'routes `error_path(:error) to #show`' do expect(get error_path('500')).to route_to( 'errors#show', error: '500') end end end
unindented/unindented-rails
app/views/feeds/show.atom.builder
<filename>app/views/feeds/show.atom.builder root_url = absolute_url(nil) feed_url = absolute_url(feed_path(format: :atom, trailing_slash: false)) feed_id = "tag:#{feed_url}" atom_feed(root_url: root_url, url: feed_url, id: feed_id) do |feed| feed.title(@contents.title) feed.subtitle(@contents.subtitle) feed.updated(@contents.updated) if @contents.length > 0 feed.author do |author| author.name(@contents.author) end feed.rights(@contents.copyright) @contents.each do |content| content_url = absolute_url(content.route) content_id = "tag:#{content_url}" feed.entry(content, url: content_url, id: content_id) do |entry| entry.title(content.title) entry.updated(content.datetime) entry.author do |author| author.name(content.author) end content.tags.each do |tag| entry.category(term: tag.to_param, label: tag.name) end entry.summary(content.abstract) entry.content(content.body_html, type: :html) end end end
unindented/unindented-rails
lib/pygments_processor.rb
require 'htmlentities' require 'nokogiri' require 'pygments' class PygmentsProcessor DEFAULT_LANG = 'text' DEFAULT_OPTS = { elements: ['pre', 'code'], attribute: 'class', pattern: /language-(?<lang>\w+)/, misc: {} } def initialize(opts = {}) @coder = ::HTMLEntities.new @opts = DEFAULT_OPTS.merge(opts) end def process(str) doc = ::Nokogiri::HTML::DocumentFragment.parse(str) search(doc).each { |node| highlight(node) } doc.to_html end private def search(doc) doc.css(@opts[:elements].join('>')) end def highlight(node) lang = extract_lang(node) code = @coder.decode(extract_html(node)) target = find_parent(node) target.swap(pygments(lang, code, @opts[:misc].clone)) end def extract_lang(node) attr = node[@opts[:attribute]] ((attr && @opts[:pattern].match(attr)) || { lang: DEFAULT_LANG })[:lang] end def extract_html(node) node.inner_html end def find_parent(node) target = node (@opts[:elements].length - 1).times { target = target.parent } target end def pygments(lang, code, opts = {}) ::Pygments.highlight(code, formatter: 'html', lexer: lang, options: opts) end end
unindented/unindented-rails
spec/decorators/content_decorator_spec.rb
describe ContentDecorator do describe '#datetime' do it 'returns the date in long ISO 8601 format' do content = FactoryGirl.build(:content).decorate expect(content.datetime.to_s).to match(/\d{4}-\d{2}-\d{2}T00:00:00\+00:00/) end end describe '#related' do let (:content) { FactoryGirl.build(:content).decorate } let (:related) { double(decorate: true, previous: nil, next: nil) } context 'with next content' do before do allow(content).to receive(:previous).and_return(nil) allow(content).to receive(:next).and_return(related) end it 'returns an array with the next content' do expect(content.related).to have(1).item expect(related).to have_received(:decorate) end end context 'with previous content' do before do allow(content).to receive(:next).and_return(nil) allow(content).to receive(:previous).and_return(related) end it 'returns an array with the previous content' do expect(content.related).to have(1).item expect(related).to have_received(:decorate) end end context 'with no next or previous content' do before do allow(content).to receive(:next).and_return(nil) allow(content).to receive(:previous).and_return(nil) end it 'returns an empty array' do expect(content.related).to be_empty end end end describe '#route' do it 'returns the route for the content' do content = FactoryGirl.build(:content).decorate expect(content.route).to eq(helpers.content_path(content)) end end describe '#parent_route' do it 'returns the parent route for the content' do content = FactoryGirl.build(:content, category: :articles).decorate expect(content.parent_route).to eq(helpers.archive_articles_path) end end describe '#previous_route' do let (:content) { FactoryGirl.build(:content).decorate } let (:related) { double(decorate: double(route: 'foobar')) } context 'with previous content' do before do allow(content).to receive(:previous).and_return(related) end it 'returns the route for the previous content' do expect(content.previous_route).to eq(related.decorate.route) end end end describe '#next_route' do let (:content) { FactoryGirl.build(:content).decorate } let (:related) { double(decorate: double(route: 'foobar')) } context 'with next content' do before do allow(content).to receive(:next).and_return(related) end it 'returns the route for the next content' do expect(content.next_route).to eq(related.decorate.route) end end end describe '#date_route' do it 'returns the date route for the content' do content = FactoryGirl.build(:content, category: :articles, date: Date.new(2013, 2, 1)).decorate expect(content.date_route).to eq(helpers.archive_articles_path(year: '2013', month: '02', day: '01')) end end describe '#block_link' do it 'generates a link to the content with the result of a block' do content = FactoryGirl.build(:content).decorate link = Capybara.string(content.block_link { 'Foo' }) expect(link).to have_xpath("//a[@href='#{content.route}']") expect(link).to have_text('Foo') end end describe '#title_link' do it 'generates a link to the content with its title as text' do content = FactoryGirl.build(:content).decorate link = Capybara.string(content.title_link) expect(link).to have_xpath("//a[@href='#{content.route}']") expect(link).to have_text(content.title) end end describe '#date_link' do it 'generates a link to the archive with its date as text' do content = FactoryGirl.build(:content).decorate link = Capybara.string(content.date_link) expect(link).to have_xpath("//a[@href='#{content.date_route}']/time") expect(link).to have_text(helpers.l(content.date, format: :day)) end end describe '#tags_list' do it 'generates a list of links with the content tags' do tags = FactoryGirl.create_list(:tag, 3) content = FactoryGirl.build(:content).decorate content.tags << tags list = Capybara.string(content.tags_list) expect(list).to have_xpath("//li/a[@rel='tag']", count: tags.length) end end end
unindented/unindented-rails
spec/controllers/contents_controller_spec.rb
<gh_stars>0 describe ContentsController do describe 'GET show' do let!(:content) { FactoryGirl.create(:content, locator: 'foobar') } context 'with incorrect locator' do it 'has a 404 status code' do get :show, locator: 'bazqux' expect(response.status).to eq(404) end end context 'with correct locator' do it 'has a 200 status code' do get :show, locator: 'foobar' expect(response.status).to eq(200) end end context 'with correct locator but incorrect filename' do it 'has a 404 status code' do path = File.join([Rails.root, 'contents', content.path, 'bazqux.png']) allow(File).to receive(:read).with(path).and_raise(Errno::ENOENT) get :show, locator: 'foobar', filename: 'bazqux.png' expect(response.status).to eq(404) end end context 'with correct locator and correct filename' do it 'has a 200 status code' do path = File.join([Rails.root, 'contents', content.path, 'bazqux.png']) allow(File).to receive(:read).with(path).and_return(double()) get :show, locator: 'foobar', filename: 'bazqux.png' expect(response.status).to eq(200) end end end end
unindented/unindented-rails
config/environments/test.rb
<reponame>unindented/unindented-rails<filename>config/environments/test.rb Rails.application.configure do config.cache_classes = true config.eager_load = false config.serve_static_assets = true config.static_cache_control = "public, max-age=#{1.hour.to_i}" config.consider_all_requests_local = true config.action_controller.perform_caching = false config.action_controller.allow_forgery_protection = false config.action_controller.default_url_options = { trailing_slash: true } config.active_support.deprecation = :stderr config.action_dispatch.show_exceptions = false end
unindented/unindented-rails
config/application.rb
<reponame>unindented/unindented-rails require File.expand_path('../boot', __FILE__) require 'active_record/railtie' require 'action_controller/railtie' require 'sprockets/railtie' Bundler.require(:default, Rails.env) module Website class Application < Rails::Application config.autoload_paths += %W(#{config.root}/lib) end end
unindented/unindented-rails
app/controllers/errors_controller.rb
class ErrorsController < ArchivesController def show render params[:error], layout: 'errors' end end
unindented/unindented-rails
spec/lib/pygments_processor_spec.rb
<gh_stars>0 describe PygmentsProcessor do subject do PygmentsProcessor.new(misc: { cssclass: 'highlighted' }) end describe '#process' do it 'highlights a preformatted block' do body = Capybara.string(subject.process(<<-eos <pre> <code class="language-sh">echo 'Foo!'</code> </pre> eos )) expect(body).to have_xpath('//div[@class="highlighted"]/pre') end end end
unindented/unindented-rails
db/migrate/20131201000003_create_content_tags.rb
<reponame>unindented/unindented-rails class CreateContentTags < ActiveRecord::Migration def change create_table :content_tags do |t| t.belongs_to :content, null: false, index: true t.belongs_to :tag, null: false, index: true end end end
unindented/unindented-rails
spec/routing/contents_routing_spec.rb
<reponame>unindented/unindented-rails<filename>spec/routing/contents_routing_spec.rb describe ContentsController do describe 'routing' do it 'routes `/about` to #show' do expect(get '/about/').to route_to( 'contents#show', locator: 'about') end it 'routes `/articles/foobar` to #show' do expect(get '/articles/foobar/').to route_to( 'contents#show', locator: 'articles/foobar') end it 'routes `/articles/foobar/image.png` to #show' do expect(get '/articles/foobar/image.png').to route_to( 'contents#show', locator: 'articles/foobar', filename: 'image.png') end it 'routes `/experiments/foobar` to #show' do expect(get '/experiments/foobar/').to route_to( 'contents#show', locator: 'experiments/foobar') end it 'routes `/experiments/foobar/image.png` to #show' do expect(get '/experiments/foobar/image.png').to route_to( 'contents#show', locator: 'experiments/foobar', filename: 'image.png') end end describe 'named routes' do it 'routes `content_path(:locator) to #show`' do expect(get content_path('foobar')).to route_to( 'contents#show', locator: 'foobar') end it 'routes `file_content_path(:locator, :filename) to #show`' do expect(get file_content_path(locator: 'foobar', filename: 'bazqux.png')).to route_to( 'contents#show', locator: 'foobar', filename: 'bazqux.png') end end end
unindented/unindented-rails
config/initializers/secret_token.rb
Rails.application.config.secret_key_base = SecureRandom.hex(30)
unindented/unindented-rails
spec/helpers/twitter_helper_spec.rb
<reponame>unindented/unindented-rails describe TwitterHelper do describe '#twitter_card_meta_tag' do it 'returns a Twitter Card meta tag with the specified name and value' do meta = Capybara.string(helper.twitter_card_meta_tag(:card, :summary)) expect(meta).to have_xpath("//meta[@name='twitter:card']", visible: false) expect(meta).to have_xpath("//meta[@content='summary']", visible: false) end end end
unindented/unindented-rails
spec/routing/feeds_routing_spec.rb
describe FeedsController do describe 'routing' do it 'routes `/feed.atom` to #show' do expect(get '/feed.atom').to route_to('feeds#show', format: 'atom') end it 'routes `/feed.tile` to #show' do expect(get '/feed.tile').to route_to('feeds#show', format: 'tile') end end describe 'named routes' do it 'routes `feed_path(format :atom)` to #show' do expect(get feed_path(format: :atom)).to route_to('feeds#show', format: 'atom') end it 'routes `feed_path(format: :tile)` to #show' do expect(get feed_path(format: :tile)).to route_to('feeds#show', format: 'tile') end end end
unindented/unindented-rails
app/controllers/experiments_controller.rb
<filename>app/controllers/experiments_controller.rb class ExperimentsController < ArchivesController end
unindented/unindented-rails
config/initializers/bullet.rb
if defined? Bullet Bullet.enable = true Bullet.bullet_logger = true Bullet.rails_logger = true end
unindented/unindented-rails
app/decorators/content_decorator.rb
class ContentDecorator < ModelDecorator delegate_all def datetime DateTime.parse(date.to_s) end def color (self.id % 6) + 1 end def related p = self.previous n = self.next pp = p && p.previous nn = n && n.next rel = [pp, p, n, nn].compact rel.slice((rel.length - 1) / 2.0, 2).map(&:decorate) end def route content_path(self) end def parent_route send("archive_#{category}_path") end def previous_route p = self.previous p.decorate.route if p.present? end def next_route n = self.next n.decorate.route if n.present? end def date_route array = [date.year, date.month, date.day].map { |v| v.to_s.rjust(2, '0') } send("archive_#{category}_path", Hash[[:year, :month, :day].zip(array)]) end def block_link(options = {}, &block) link_to(route, options, &block) end def title_link(options = {}) link_to(title, route, options.symbolize_keys) end def date_link(options = {}) link_to(time_tag(date, format: :day), date_route, { class: :date }.merge!(options.symbolize_keys)) end def tags_links() tags.map do |tag| link_to(tag.name, tag_path(tag), class: :tag, rel: :tag) end end def tags_list(options = {}) return if tags.length == 0 items = tags_links.reduce('') do |memo, link| item = content_tag(:li, link) memo + item end content_tag(:ul, items.html_safe, { class: :tags, role: :navigation }.merge!(options.symbolize_keys)) end end
unindented/unindented-rails
app/decorators/contents_decorator.rb
<reponame>unindented/unindented-rails class ContentsDecorator < CollectionDecorator delegate :current_page, :total_pages, :limit_value def title title_text end def subtitle subtitle_text end def updated first.datetime end def author author_text end def copyright copyright_text end end
unindented/unindented-rails
features/step_definitions/javascript_steps.rb
<reponame>unindented/unindented-rails Then(/^I should (not )?see the variable "([^"]*)"(?: with the value "([^"]*)")?$/) do |negate, variable, value| if value.present? script = variable matcher = eq(value) method = negate.present? ? 'to_not' : 'to' else script = "typeof #{variable}" matcher = eq('undefined') method = negate.present? ? 'to' : 'to_not' end expect(page.evaluate_script(script)).send(method, matcher) end
unindented/unindented-rails
db/migrate/20131201000004_create_extensions.rb
class CreateExtensions < ActiveRecord::Migration def change create_table :extensions do |t| t.string :name, null: false t.string :locator, null: false, index: true end end end
unindented/unindented-rails
spec/factories/contents.rb
FactoryGirl.define do factory(:content) do title { Faker::Lorem::words(Random.rand(4) + 4).join(' ') } author { Faker::Name::name } body { Faker::Lorem::paragraphs(Random.rand(5) + 5).join("\n\n") } category { %w{articles experiments}[Random.rand(2)] } date { Date.today - Random.rand(3333) } path { "#{category}/#{date}-#{(title || '').parameterize}" } locator { "#{category}/#{(title || '').parameterize}" } end end
unindented/unindented-rails
lib/tasks/icons.rake
<filename>lib/tasks/icons.rake<gh_stars>0 require 'icon_generator' namespace :icons do namespace :favicon do desc 'Build favicon in SVG format' task :svg do src = Rails.root.join('app', 'assets', 'images', 'logo_stroked.svg') dst = Rails.root.join('public', 'favicon.svg') FileUtils.cp(src, dst) end desc 'Build favicon in PNG format' task :png => 'icons:favicon:svg' do src = Rails.root.join('public', 'favicon.svg') dst = Rails.root.join('public') sizes = { '48x48' => 48, '32x32' => 32, '24x24' => 24, '16x16' => 16, nil => 32 } IconGenerator.new.png(src, sizes: sizes) do |name, options| suffix = "-#{name}" if name.present? dst.join("favicon#{suffix}.png") end end desc 'Build favicon in ICO format' task :ico => 'icons:favicon:png' do src = Rails.root.join('public', 'favicon-48x48.png') dst = Rails.root.join('public') sizes = { nil => [48, 32, 24, 16] } IconGenerator.new.ico(src, sizes: sizes) do |name, options| suffix = "-#{name}" if name.present? dst.join("favicon#{suffix}.ico") end end end desc 'Build Apple icons' task :apple => 'icons:favicon:svg' do src = Rails.root.join('public', 'favicon.svg') dst = Rails.root.join('public') sizes = { '144x144-precomposed' => 144, '120x120-precomposed' => 120, '114x114-precomposed' => 114, '72x72-precomposed' => 72, '57x57-precomposed' => 57, 'precomposed' => 57, nil => 57 } IconGenerator.new.png(src, sizes: sizes) do |name, options| suffix = "-#{name}" if name.present? dst.join("apple-touch-icon#{suffix}.png") end end desc 'Build Microsoft icons' task :microsoft => 'icons:favicon:svg' do src = Rails.root.join('public', 'favicon.svg') dst = Rails.root.join('public') sizes = { '558x558' => 558, '270x270' => 270, '128x128' => 128 } IconGenerator.new.png(src, sizes: sizes) do |name, options| suffix = "-#{name}" if name.present? dst.join("ms-touch-icon#{suffix}.png") end end desc 'Build all icons' task :all => ['icons:favicon:png', 'icons:favicon:ico', 'icons:apple', 'icons:microsoft'] end desc 'Alias for icons:all' task :icons => 'icons:all'
unindented/unindented-rails
spec/models/content_taggable_spec.rb
describe Content do describe '#tags_list' do let(:tags) do tags = [] tags << FactoryGirl.build(:tag, name: 'Foo') tags << FactoryGirl.build(:tag, name: 'Bar') end it 'returns an empty array when there are no tags' do content = FactoryGirl.build(:content) expect(content.tags_list).to be_empty end it 'returns an array with the tag names' do content = FactoryGirl.build(:content) content.tags << tags expect(content.tags_list).to include('Foo', 'Bar') end end describe '#tags_list=' do let(:tags) do tags = [] tags << FactoryGirl.build(:tag, name: 'Foo') tags << FactoryGirl.build(:tag, name: 'Bar') end it 'clears all previous tags' do content = FactoryGirl.build(:content) content.tags << tags content.tags_list = [] expect(content.tags_list).to be_empty end it 'assigns the specified tags' do content = FactoryGirl.build(:content) content.tags << tags content.tags_list = ['Foo', 'Baz'] expect(content.tags_list).to include('Foo', 'Baz') expect(content.tags_list).to_not include('Bar') end end end
unindented/unindented-rails
spec/helpers/open_graph_helper_spec.rb
<reponame>unindented/unindented-rails describe OpenGraphHelper do describe '#open_graph_meta_tag' do it 'returns an Open Graph meta tag with the specified name and value' do meta = Capybara.string(helper.open_graph_meta_tag(:type, :website)) expect(meta).to have_xpath("//meta[@property='og:type']", visible: false) expect(meta).to have_xpath("//meta[@content='website']", visible: false) end end end
unindented/unindented-rails
lib/tasks/glyphs.rake
<filename>lib/tasks/glyphs.rake<gh_stars>0 namespace :glyphs do desc 'Build all glyphs' task :all do puts %x(fontcustom compile) end end desc 'Alias for glyphs:all' task :glyphs => 'glyphs:all'
unindented/unindented-rails
spec/factories/tags.rb
FactoryGirl.define do sequence :tag_name do |n| "tag#{n}" end factory(:tag) do name { FactoryGirl.generate(:tag_name) } end end
unindented/unindented-rails
app/models/concerns/summarizable.rb
<filename>app/models/concerns/summarizable.rb module Summarizable extend ActiveSupport::Concern included do summarizer = BodySummarizer.new define_method(:summarize_text) { |body_html| summarizer.summarize_text(body_html) } define_method(:summarize_html) { |body_html| summarizer.summarize_html(body_html) } end end
unindented/unindented-rails
spec/helpers/text_helper_spec.rb
describe TextHelper do describe '#host_text' do it 'returns the host of the site' do allow(SETTINGS).to receive(:host) { 'http://www.foo.com' } expect(helper.host_text).to eq('http://www.foo.com') end end describe '#website_text' do it 'returns the name of the site' do allow(SETTINGS).to receive(:website) { 'FooBar' } expect(helper.website_text).to eq('FooBar') end end describe '#author_text' do it 'returns the author of the site' do allow(SETTINGS).to receive(:author) { '<NAME>' } expect(helper.author_text).to eq('<NAME>') end end describe '#email_text' do it 'returns the email of the creator' do allow(SETTINGS).to receive(:email) { '<EMAIL>' } expect(helper.email_text).to eq('<EMAIL>') end end describe '#twitter_text' do it 'returns the Twitter handle of the creator' do allow(SETTINGS).to receive(:twitter) { 'foobar' } expect(helper.twitter_text).to eq('foobar') end end describe '#github_text' do it 'returns the GitHub handle of the creator' do allow(SETTINGS).to receive(:github) { 'foobar' } expect(helper.github_text).to eq('foobar') end end describe '#title_text' do it 'returns the title of the site' do allow(SETTINGS).to receive(:website) { 'FooBar' } title = t(:title, website: 'FooBar') expect(helper.title_text).to eq(title) end end describe '#subtitle_text' do it 'returns the subtitle of the site' do allow(SETTINGS).to receive(:author) { '<NAME>' } subtitle = t(:subtitle, author: '<NAME>') expect(helper.subtitle_text).to eq(subtitle) end end describe '#copyright_text' do it 'returns the subtitle of the site' do allow(SETTINGS).to receive(:author) { '<NAME>' } copyright = t('shared.page_meta.copyright', author: '<NAME>', license: t('shared.page_meta.license') ) expect(helper.copyright_text).to eq(copyright) end end end
FrenchKit/UIAutomationClassroom
mock-server/test_run.rb
<reponame>FrenchKit/UIAutomationClassroom class TestRun < ActiveRecord::Base has_many :tracking_events, :dependent => :destroy has_many :mock_responses, :dependent => :destroy end
FrenchKit/UIAutomationClassroom
mock-server/db/migrate/20170717103415_setup.rb
class Setup < ActiveRecord::Migration[5.1] def change create_table :test_runs do |t| t.string :name t.timestamp :started t.timestamp :ended t.timestamps end add_index :test_runs, :name, unique: true create_table :tracking_events do |t| t.text :content t.integer :test_run_id t.timestamps end add_foreign_key :tracking_events, :test_runs create_table :mock_responses do |t| t.string :url t.string :parameters t.string :method t.integer :response_status_code t.text :response_body t.integer :test_run_id end add_foreign_key :mock_responses, :test_runs end end
FrenchKit/UIAutomationClassroom
mock-server/db/migrate/20170804120735_add_mime_encoding.rb
<filename>mock-server/db/migrate/20170804120735_add_mime_encoding.rb class AddMimeEncoding < ActiveRecord::Migration[5.1] def change add_column :mock_responses, :response_mime_type, :string add_column :mock_responses, :response_encoding, :string end end
FrenchKit/UIAutomationClassroom
mock-server/mock_response.rb
<filename>mock-server/mock_response.rb class MockResponse < ActiveRecord::Base belongs_to :test_run end
FrenchKit/UIAutomationClassroom
mock-server/mock-server.rb
#! /usr/bin/env ruby require 'sinatra/base' require 'json' require 'active_record' require 'thin' require 'base64' require './test_run' require './mock_response' ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'mockdb.sqlite3.db', :pool => 30, :timeout => 1000 ) class MockServer < Sinatra::Base configure do set :bind, '0.0.0.0' set :server, 'thin' enable :logging end get '/hello-world' do response = { response: "Hello world!" } echo = params["echo"] unless echo.nil? response["echo"] = echo end json(response) end # check for required parameters before /\/(test|mock)/ do @test_name = params['test_name'] || env['HTTP_X_TEST_NAME'] halt 400, "test_name is missing" unless @test_name @test_run = TestRun.find_by(name: @test_name) end # clear connections otherwise connection pool gets drained quickly after do ActiveRecord::Base.clear_active_connections! end post '/test' do TestRun.create do |t| t.name = @test_name t.started = Time.now end end delete '/test' do validate_test_run @test_run.destroy end def validate_test_run unless @test_run logger.error "=> No test running! Start first" halt 400, "test run not found. Did you post to /test first?" end end # reads body as a newline delimited events # each line is a tracking event post '/tracking-log-batch' do validate_test_run if request.body.size > 0 request.body.rewind request.body.readlines.each do |l| TrackingEvent.create do |e| e.content = l.strip e.test_run = @test_run end end end end post '/mock' do # store mock response for a request validate_test_run path = URI.parse(params['url']).path unless params['file'] logger.info "missing response body #{path}" halt 500, "missing response body" end MockResponse.create do |r| r.url = path r.method = params['method'] r.parameters = params['parameters'] r.response_mime_type = params['mime_type'] r.response_encoding = params['encoding'] r.response_status_code = params['status_code'] raw_body = params['file'][:tempfile].read body = params['encoding'] == 'base64' ? raw_body : raw_body.force_encoding(params['encoding']) r.response_body = body r.test_run = @test_run end logger.info "=> Created mock for path #{path}" end def handle_all_requests(request, params, method) r = MockResponse.find_by(url: request.path_info, method: method) halt 404, "mock response not found" unless r set_headers(r.response_mime_type) status r.response_status_code body case r.response_encoding when 'base64' Base64.decode64(r.response_body) else r.response_body end end get '/*' do handle_all_requests(request, params, 'GET') end post '/*' do handle_all_requests(request, params, 'POST') end put '/*' do handle_all_requests(request, params, 'PUT') end delete '/*' do handle_all_requests(request, params, 'DELETE') end not_found do json({ error: "Not Found" }) end def json_file(name) set_headers("application/json") File.read(File.join(File.dirname(__FILE__), name)) end def set_headers(mimeType) headers "Content-Type" => mimeType end def json(body) set_headers("application/json") JSON.generate(body) end run! if app_file == $0 end
JDC1492/vg_organizer-project
db/migrate/20201005133035_create_games_table.rb
<reponame>JDC1492/vg_organizer-project<filename>db/migrate/20201005133035_create_games_table.rb<gh_stars>0 class CreateGamesTable < ActiveRecord::Migration[5.2] def change create_table :games do |t| t.string :title t.string :console t.string :genre t.string :description t.boolean :complete, default: false end end end
JDC1492/vg_organizer-project
app/controllers/games_controller.rb
<gh_stars>0 class GamesController < ApplicationController get '/games' do redirect_if_not_logged_in @games = current_user.games erb :'games/index' end get '/games/new' do redirect_if_not_logged_in erb :'games/new' end get '/games/:id' do redirect_if_not_logged_in @game = Game.find_by_id(params[:id]) if current_user.id == @game.user.id erb :'games/show' else redirect '/games' end end post '/games' do if logged_in? @user = current_user new_game=Game.new(params) if new_game.save #dependent on validations @user.games << new_game redirect "games/#{new_game.id}" else redirect 'games/new' end end end get '/games/:id/edit' do redirect_if_not_logged_in @game = Game.find_by_id(params[:id]) if @game.user.id == current_user.id erb :'/games/edit' else redirect to "/games" end end patch '/games/:id' do @user = current_user @game = Game.find_by_id(params[:id]) params.delete("_method") if @user.id == @game.user.id if @game.update(params) # @user.games << @game redirect "/games/#{@game.id}" else redirect "/games" end end end delete '/games/:id' do @game = Game.find_by_id(params[:id]) if current_user.id == @game.user.id @game.destroy end redirect "/games" end end
JDC1492/vg_organizer-project
app/controllers/users_controller.rb
<filename>app/controllers/users_controller.rb<gh_stars>0 class UsersController < ApplicationController get '/signup' do @user = User.new(params) erb :'/users/sign_up' end post '/signup' do user = User.new(params) if user.save && user.authenticate(params[:password]) session[:user_id] = user.id redirect "/games" else redirect '/signup' end end end
Revolutionary-Games/ThriveDevCenter
ef.rb
<filename>ef.rb #!/usr/bin/env ruby # frozen_string_literal: true # Helper script to run dotnet-ef tool require 'English' require 'optparse' @options = { install: false, update: false, create: nil } SERVER_PROJECT_FILE = 'Server/ThriveDevCenter.Server.csproj' ASP_NET_VERSION_REGEX = /Include="Microsoft\.AspNetCore\..+" Version="([0-9.]+)"/.freeze OptionParser.new do |opts| opts.banner = "Usage: #{$PROGRAM_NAME} [options]" opts.on('-i', '--[no-]install', 'Install the tool') do |install| @options[:install] = install end opts.on('-u', '--[no-]update', 'Update the tool') do |update| @options[:update] = update end opts.on('-c', '--create MIGRATION_NAME', 'Create a new migration') do |create| @options[:create] = create end end.parse! abort "Unhandled parameters: #{ARGV}" unless ARGV.empty? def detect_version File.foreach(SERVER_PROJECT_FILE) do |line| match = line.match(ASP_NET_VERSION_REGEX) if match puts "Detected wanted aspnet version: #{match[1]}" return match[1] end end abort('could not detect wanted aspnet version') end if @options[:install] puts 'Installing dotnet-ef tool' system 'dotnet', 'tool', 'install', '--global', 'dotnet-ef', '--version', detect_version abort('failed to install') if $CHILD_STATUS.exitstatus != 0 end if @options[:update] puts 'Installing dotnet-ef tool' system 'dotnet', 'tool', 'update', '--global', 'dotnet-ef', '--version', detect_version abort('failed to update') if $CHILD_STATUS.exitstatus != 0 end puts 'Finished operations'
Revolutionary-Games/ThriveDevCenter
fix_boot_json_hashes.rb
<filename>fix_boot_json_hashes.rb # frozen_string_literal: true require 'json' require 'fileutils' require 'zlib' require 'digest' require 'English' # Fixes all incorrect hashes in a blazor.boot.json file def fix_boot_json_hashes(path_to_boot) data = JSON.parse File.read(path_to_boot) changes = process_hash_helper File.dirname(path_to_boot), data return unless changes puts "Detected invalid hashes in #{path_to_boot} recreating the file" # Only write out if we made changes File.write path_to_boot, JSON.pretty_generate(data, { indent: ' ' }) regenerate_compressed_files path_to_boot end def process_hash_helper(base_path, value) changes = false value.each { |key, child_value| if child_value.is_a? Hash changes = true if process_hash_helper(base_path, child_value) elsif child_value.is_a?(String) && child_value.include?('sha256-') # Detected a value that contains a hash correct = calculate_file_sha256_base64(File.join(base_path, key)) if correct != child_value puts "Invalid hash detected for entry: #{key}" value[key] = correct changes = true end end } changes end def regenerate_compressed_files(path) gzipped = path + '.gz' FileUtils.rm_f gzipped Zlib::GzipWriter.open(gzipped, Zlib::BEST_COMPRESSION) { |gz| gz.mtime = File.mtime(path) gz.orig_name = path gz.write IO.binread(path) } brotlied = path + '.br' FileUtils.rm_f brotlied # TODO: would it be better to require installing the brotli gem # rather than depend on system installed tool? system('brotli', '-9ko', brotlied, path) raise 'failed to brotli compress' if $CHILD_STATUS.exitstatus != 0 end def calculate_file_sha256_base64(file) sha256 = Digest::SHA256.file file "sha256-#{sha256.base64digest}" end
Revolutionary-Games/ThriveDevCenter
deploy.rb
<gh_stars>1-10 #!/usr/bin/env ruby # frozen_string_literal: true # ThriveDevCenter deploy require 'English' require 'optparse' require_relative 'fix_boot_json_hashes' @options = { mode: 'staging', # TODO: add running only specific migrations mode migration: 'idempotent', use_migrations: true, use_deploy: true } # TODO: make this possible to configure from the command line MODE = 'Release' CLIENT_BUILT_WEBROOT = "Client/bin/#{MODE}/net5.0/publish/wwwroot/" SERVER_BUILT_BASE = "Server/bin/#{MODE}/net5.0/publish/" CI_EXECUTOR_BUILT_FILE = "CIExecutor/bin/#{MODE}/net5.0/linux-x64/publish/CIExecutor" CI_EXECUTOR_EXTRA_RESOURCES = ["CIExecutor/bin/#{MODE}/net5.0/linux-x64/" \ 'libMonoPosixHelper.so'].freeze OptionParser.new do |opts| opts.banner = "Usage: #{$PROGRAM_NAME} [options]" opts.on('-m', '--mode MODE', 'Deploy mode. staging or production') do |mode| @options[:mode] = mode end # opts.on('-t', '--migration-type TYPE', # 'Type of migration to perform') do |type| # @options[:migration] = type # end opts.on('--skip-migrations', 'Skip applying migrations') do |_f| @options[:use_migrations] = false end opts.on('--skip-deploy', 'Skip actually deploying the code to the server') do |_f| @options[:use_deploy] = false end end.parse! abort "Unhandled parameters: #{ARGV}" unless ARGV.empty? abort 'Invalid mode' unless %w[staging production].include?(@options[:mode]) abort 'Invalid migration type' unless %w[idempotent].include?(@options[:migration]) TARGET_HOST_WWW_ROOT = "/var/www/thrivedevcenter/#{@options[:mode]}" TARGET_HOST_APP_ROOT = "/opt/thrivedevcenter/#{@options[:mode]}" target_host = if @options[:mode] == 'production' 'dev.revolutionarygamesstudio.com' else 'staging.dev.revolutionarygamesstudio.com' end @db_name = if @options[:mode] == 'production' 'thrivedevcenter' else 'thrivedevcenter_staging' end puts "Starting deploy to: #{target_host}" # TODO: send site notification about the impending downtime def grant_type(type) if type == 'SEQUENCES' 'GRANT USAGE, SELECT, UPDATE ON ALL SEQUENCES IN SCHEMA public TO ' \ "#{@db_name};" else "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL #{type} IN SCHEMA public TO " \ "#{@db_name};" end end if @options[:use_migrations] puts 'Generating migration' system('dotnet', 'ef', 'migrations', 'script', '--idempotent', '--project', 'Server/ThriveDevCenter.Server.csproj', '--context', 'ApplicationDbContext', '-o', 'migration.sql') abort('failed to create migration') if $CHILD_STATUS.exitstatus != 0 puts "Please check 'migration.sql' for accuracy, then press enter to continue "\ '(or CTRL-C to cancel)' _ = gets puts 'Sending migration to server' system('scp', 'migration.sql', "root@#{target_host}:migration.sql") abort('failed to copy migration to server') if $CHILD_STATUS.exitstatus != 0 puts 'Running migration...' # TODO: would be nice to only show the output here if failed system('ssh', "root@#{target_host}", "su - postgres -c \"psql -d #{@db_name}\" < migration.sql") abort('failed to run migration') if $CHILD_STATUS.exitstatus != 0 puts 'Trying to fudge grants...' # Here it is assumed that db name is the same as the user name system('ssh', "root@#{target_host}", "su - postgres -c \"psql -d #{@db_name} -c '#{grant_type 'TABLES'}" \ "#{grant_type 'SEQUENCES'}'\"") abort('grants change failed') if $CHILD_STATUS.exitstatus != 0 puts "Migration complete. Building #{MODE} files" else puts "Building #{MODE} files" end system('dotnet', 'publish', '-c', MODE) abort('failed to build') if $CHILD_STATUS.exitstatus != 0 puts 'Making sure blazor.boot.json has correct hashes' Dir.glob("#{CLIENT_BUILT_WEBROOT}**/blazor.boot.json") { |file| puts "Checking boot file: #{file}" fix_boot_json_hashes file } puts 'Build finished. Sending files' unless @options[:use_deploy] puts 'Skipping deploy' exit 0 end # Copy the CI executor to the webroot to be able to serve it FileUtils.cp CI_EXECUTOR_BUILT_FILE, CLIENT_BUILT_WEBROOT regenerate_compressed_files File.join(CLIENT_BUILT_WEBROOT, 'CIExecutor') # And it also needs extra files... CI_EXECUTOR_EXTRA_RESOURCES.each { |resource| FileUtils.cp resource, CLIENT_BUILT_WEBROOT regenerate_compressed_files File.join(CLIENT_BUILT_WEBROOT, File.basename(resource)) } system('rsync', '-hr', CLIENT_BUILT_WEBROOT, "root@#{target_host}:#{TARGET_HOST_WWW_ROOT}", '--delete') abort('failed to send files') if $CHILD_STATUS.exitstatus != 0 # App settings is excluded as it has development environment secrets system('rsync', '-hr', SERVER_BUILT_BASE, "root@#{target_host}:#{TARGET_HOST_APP_ROOT}", '--delete', '--exclude', 'appsettings.Development.json', '--exclude', 'wwwroot') abort('failed to send files (server)') if $CHILD_STATUS.exitstatus != 0 puts 'Files synced to server' puts 'Deploy finished. Restarting services on the server' if @options[:mode] == 'production' system('ssh', "root@#{target_host}", 'systemctl restart thrivedevcenter') else system('ssh', "root@#{target_host}", 'systemctl restart thrivedevcenter-staging') end abort('failed to restart services') if $CHILD_STATUS.exitstatus != 0
abdoutelb/reminder
spec/services/email_notification_spec.rb
<filename>spec/services/email_notification_spec.rb require "rails_helper" describe EmailNotification do describe "#sending email" do it "check output for sending ticket" do EmailNotification.send(Ticket.first).should eql("This ticket task went to <EMAIL>") end end end
abdoutelb/reminder
app/helpers/notify_helper.rb
module NotifyHelper def self.send_ticket(ticket) NotifyHelper::Notification.new().send(ticket) end class Notification RegisterServices = ["EmailNotification"] def send(ticket) RegisterServices.each do |service| Object.const_get(service).send(ticket); end end end end
abdoutelb/reminder
spec/factories/tickets.rb
FactoryBot.define do factory :ticket do title { Faker::Name.name } description { Faker::Lorem.paragraph } due_date { Time.now } status_id { 0 } progress { Faker::Number.number(2) } user_id { User.first ? User.first.id : create(:user).id } end end
abdoutelb/reminder
app/models/user.rb
<filename>app/models/user.rb class User < ApplicationRecord validates_presence_of :name, :email, :send_due_date_reminder ,:send_due_reminder_interval, :due_date_reminder_time, :time_zone def activate self.update(send_due_date_reminder: true) end def prefered_time self.due_date_reminder_time - self.send_due_reminder_interval.hours end def deactivate self.update(send_due_date_reminder: false) end def set_interval(time) self.update(send_due_reminder_interval: time) end def set_recived_due_date(time) self.update(due_date_reminder_time: time) end def set_time_zone(time) self.update(time_zone: time) end end
abdoutelb/reminder
app/models/ticket.rb
class Ticket < ApplicationRecord NOT_DELIVED = 0 DELIVED = 1 validates_presence_of :title belongs_to :user after_create do NotifyHelper.send_ticket(self) if self.user.send_due_date_reminder? end def sent self.update(status_id: Ticket::DELIVED) end end
abdoutelb/reminder
app/services/email_notification.rb
class EmailNotification require 'sendgrid-ruby' include SendGrid def self.send(ticket) user = ticket.user sent_at = (user.prefered_time).to_i return "This ticket #{ticket.title} went to #{user.email}" if ENV['RAILS_ENV'] == 'test' puts "This ticket #{ticket.title} went to #{user.email}" data = '{ "personalizations": [ { "send_at": %{time} , "to": [ { "email": "%{email}" } ], "subject": "%{subject}" } ], "from": { "email": "%{from}" }, "content": [ { "type": "text/plain", "value": "%{desc}" } ] }' % {email: user.email, time: sent_at, subject: ticket.title, from: ENV['FROM_EMAIL'] ,desc:ticket.description } sg = SendGrid::API.new(api_key: ENV['SENDGRID_API']) response = sg.client.mail._('send').post(request_body: JSON.parse(data)) ticket.sent if response.status_code.start_with?("20") end end
abdoutelb/reminder
db/seeds.rb
<gh_stars>0 # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) user = User.create!(email: '<EMAIL>',name: 'abdou',send_due_date_reminder: true, send_due_reminder_interval: 0,due_date_reminder_time: Time.now ,time_zone: 'Egypt'); ticket = Ticket.create!(title: 'task',description: 'development task',user_id: user.id)
abdoutelb/reminder
spec/factories/users.rb
FactoryBot.define do factory :user do name { Faker::Name.name } email { Faker::Internet.email } send_due_reminder_interval { Faker::Number.number(2) } send_due_date_reminder { Faker::Boolean.boolean } due_date_reminder_time { Time.now } time_zone { Faker::Name.name } end end
abdoutelb/reminder
spec/models/user_spec.rb
<reponame>abdoutelb/reminder<filename>spec/models/user_spec.rb require "rails_helper" RSpec.describe User, type: :model do context "#validations" do it { is_expected.to validate_presence_of(:email) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:send_due_date_reminder) } it { is_expected.to validate_presence_of(:send_due_reminder_interval) } it { is_expected.to validate_presence_of(:due_date_reminder_time) } it { is_expected.to validate_presence_of(:time_zone) } end end
abdoutelb/reminder
db/migrate/20220129124008_add_user_to_tickets.rb
<reponame>abdoutelb/reminder class AddUserToTickets < ActiveRecord::Migration[5.2] def change add_reference :tickets, :user, foreign_key: true end end
abdoutelb/reminder
spec/models/ticket_spec.rb
require "rails_helper" RSpec.describe Ticket, type: :model do context "#validations" do it { is_expected.to validate_presence_of(:title) } end end
alainbloch-scopear/graphql-rails-generators
lib/generators/gql/templates/delete_mutation.rb
module Mutations class <%= prefixed_class_name('Delete') %> < Mutations::BaseMutation field :<%= singular_name %>, Types::<%= name %>Type, null: true argument :id, ID, required: true def resolve(id:) model = <%= class_name %>.find_by(uuid: id) authorize! <%= singular_name %>, to: :destroy? model.destroy {<%= singular_name %>: model} end end end
alainbloch-scopear/graphql-rails-generators
lib/generators/gql/templates/policy_file.rb
# frozen_string_literal: true class <%= name %>Policy < ApplicationPolicy relation_scope do |scope| scope end def index? #TODO - Policy goes here end def show? #TODO - policy goes here end def create? #TODO - Policy goes here end def update? #TODO - Policy goes here end def destroy? #TODO - Policy goes here end end
alainbloch-scopear/graphql-rails-generators
lib/generators/gql/templates/index_query.rb
# frozen_string_literal: true module Resolvers class <%= name.pluralize %> < Resolvers::BaseResolver type Types::<%= name %>Type, null: false description "Shows <%= name.downcase.pluralize %>" def resolve(id:) authorized_scope(::<%= name %>.all) end end end
alainbloch-scopear/graphql-rails-generators
lib/generators/gql/model_search_base_generator.rb
<reponame>alainbloch-scopear/graphql-rails-generators<gh_stars>0 module Gql class ModelSearchBaseGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) class_option :directory, type: :string, default: 'graphql' def generate_model_search_base gem 'search_object_graphql' template('model_search_base.rb', "app/#{options[:directory]}/resolvers/base_search_resolver.rb") end end end
alainbloch-scopear/graphql-rails-generators
lib/generators/gql/scaffold_generator.rb
require "rails/generators/named_base" require_relative 'gql_generator_base' module Gql class ScaffoldGenerator < Rails::Generators::NamedBase include GqlGeneratorBase source_root File.expand_path('../templates', __FILE__) desc "Generate create, update and delete generators for a model." class_option :name, type: :string class_option :include_columns, type: :array, default: [] class_option :superclass, type: :string, default: 'Types::BaseInputObject' class_option :namespace, type: :string, default: 'Types::Input' class_option :directory, type: :string, default: 'graphql' def scaffold generate_queries generate_policy generate_mutation('update') generate_mutation('create') generate_mutation('delete') end protected def generate_mutation(prefix) file_name = "#{prefix}_#{singular_name}" template("#{prefix}_mutation.rb", "app/#{options[:directory]}/mutations/#{class_path.join('/')}/#{file_name.underscore}.rb") insert_into_file("app/#{options[:directory]}/types/mutation_type.rb", after: " class MutationType < Types::BaseObject\n") do " field :#{file_name.camelcase(:lower)}, mutation: Mutations::#{prefixed_class_name(prefix)}\n" end end def generate_policy template("policy_file.rb", "app/policies/#{singular_name}_policy.rb") end def generate_queries template("show_query.rb", "app/#{options[:directory]}/resolvers/#{singular_name}.rb") insert_into_file("app/#{options[:directory]}/types/query_type.rb", after: " class QueryType < Types::BaseObject\n") do " field :#{singular_name.camelcase(:lower)}, resolver: Resolvers::#{singular_name.capitalize}\n" end template("index_query.rb", "app/#{options[:directory]}/resolvers/#{singular_name.pluralize}.rb") insert_into_file("app/#{options[:directory]}/types/query_type.rb", after: " class QueryType < Types::BaseObject\n") do " field :#{singular_name.pluralize.camelcase(:lower)}, resolver: Resolvers::#{singular_name.pluralize.capitalize}\n" end end end end
Promptus/ice_cube
lib/ice_cube/validations/minutely_interval.rb
module IceCube module Validations::MinutelyInterval def interval(interval) @interval = normalized_interval(interval) replace_validations_for(:interval, [Validation.new(@interval)]) clobber_base_validations(:min) self end class Validation attr_reader :interval def initialize(interval) @interval = interval end def type :min end def dst_adjust? false end def validate(step_time, start_time) t0, t1 = start_time.to_i, step_time.to_i sec = (t1 - t1 % ONE_MINUTE) - (t0 - t0 % ONE_MINUTE) minutes = sec / ONE_MINUTE offset = (minutes % interval).nonzero? interval - offset if offset end def build_s(builder) builder.base = IceCube::I18n.t('ice_cube.each_minute', count: interval) end def build_hash(builder) builder[:interval] = interval end def build_ical(builder) builder['FREQ'] << 'MINUTELY' builder['INTERVAL'] << interval unless interval == 1 end end end end
Promptus/ice_cube
spec/examples/secondly_rule_spec.rb
<filename>spec/examples/secondly_rule_spec.rb require File.dirname(__FILE__) + '/../spec_helper' module IceCube describe SecondlyRule, 'interval validation' do it 'converts a string integer to an actual int when using the interval method' do rule = Rule.secondly.interval("2") expect(rule.validations_for(:interval).first.interval).to eq(2) end it 'converts a string integer to an actual int when using the initializer' do rule = Rule.secondly("3") expect(rule.validations_for(:interval).first.interval).to eq(3) end it 'raises an argument error when a bad value is passed' do expect { rule = Rule.secondly("invalid") }.to raise_error(ArgumentError, "'invalid' is not a valid input for interval. Please pass a postive integer.") end it 'raises an argument error when a bad value is passed using the interval method' do expect { rule = Rule.secondly.interval("invalid") }.to raise_error(ArgumentError, "'invalid' is not a valid input for interval. Please pass a postive integer.") end end end
Promptus/ice_cube
spec/spec_helper.rb
require "bundler/setup" require 'ice_cube' begin require 'simplecov' SimpleCov.start rescue LoadError # okay end IceCube.compatibility = 12 DAY = Time.utc(2010, 3, 1) WEDNESDAY = Time.utc(2010, 6, 23, 5, 0, 0) WORLD_TIME_ZONES = [ 'America/Anchorage', # -1000 / -0900 'Europe/London', # +0000 / +0100 'Pacific/Auckland', # +1200 / +1300 ] RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" config.expect_with :rspec do |c| c.syntax = :expect end Dir[File.dirname(__FILE__) + '/support/**/*'].each { |f| require f } config.include WarningHelpers config.before :each do |example| if example.metadata[:requires_active_support] raise 'ActiveSupport required but not present' unless defined?(ActiveSupport) end end config.around :each do |example| if zone = example.metadata[:system_time_zone] orig_zone = ENV['TZ'] ENV['TZ'] = zone example.run ENV['TZ'] = orig_zone else example.run end end config.around :each, expect_warnings: true do |example| capture_warnings do example.run end end end
Promptus/ice_cube
spec/examples/to_yaml_spec.rb
<filename>spec/examples/to_yaml_spec.rb require File.dirname(__FILE__) + '/../spec_helper' require 'active_support/time' module IceCube describe Schedule, 'to_yaml' do before(:all) { Time.zone = 'Eastern Time (US & Canada)' } [:yearly, :monthly, :weekly, :daily, :hourly, :minutely, :secondly].each do |type| it "should make a #{type} round trip with to_yaml [#47]" do schedule = Schedule.new(t0 = Time.now) schedule.add_recurrence_rule Rule.send(type, 3) expect(Schedule.from_yaml(schedule.to_yaml).first(3).inspect).to eq(schedule.first(3).inspect) end end it 'should be able to let rules take round trips to yaml' do schedule = Schedule.new schedule.add_recurrence_rule Rule.monthly schedule = Schedule.from_yaml schedule.to_yaml rule = schedule.rrules.first rule.is_a?(MonthlyRule) end it 'should respond to .to_yaml' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.until(Time.now) #check assumption expect(schedule).to respond_to('to_yaml') end it 'should be able to make a round-trip to YAML' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.until(Time.now + 10) result1 = schedule.all_occurrences yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) result2 = schedule2.all_occurrences # compare without usecs expect(result1.map { |r| r.to_s }).to eq(result2.map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .day' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.day(:monday, :wednesday) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .day_of_month' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.monthly.day_of_month(10, 20) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .day_of_week' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.weekly.day_of_week(:monday => [1, -2]) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .day_of_year' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.yearly.day_of_year(100, 200) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .hour_of_day' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.hour_of_day(1, 2) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .minute_of_hour' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.minute_of_hour(0, 30) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .month_of_year' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.yearly.month_of_year(:april, :may) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should be able to make a round-trip to YAML with .second_of_minute' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.second_of_minute(1, 2) yaml_string = schedule.to_yaml schedule2 = Schedule.from_yaml(yaml_string) # compare without usecs expect(schedule.first(10).map { |r| r.to_s }).to eq(schedule2.first(10).map { |r| r.to_s }) end it 'should have a to_yaml representation of a rule that does not contain ruby objects' do rule = Rule.daily.day_of_week(:monday => [1, -1]).month_of_year(:april) expect(rule.to_yaml.include?('object')).to be_falsey end it 'should have a to_yaml representation of a schedule that does not contain ruby objects' do schedule = Schedule.new(Time.now) schedule.add_recurrence_rule Rule.daily.day_of_week(:monday => [1, -1]).month_of_year(:april) expect(schedule.to_yaml.include?('object')).to be_falsey end # This test will fail when not run in Eastern Time # This is a bug because to_datetime will always convert to system local time it 'should be able to roll forward times and get back times in an array - TimeWithZone', :requires_active_support => true do Time.zone = "Eastern Time (US & Canada)" start_time = Time.zone.local(2011, 11, 5, 12, 0, 0) schedule = Schedule.new(start_time) schedule = Schedule.from_yaml(schedule.to_yaml) # round trip ice_cube_start_time = schedule.start_time expect(ice_cube_start_time).to eq(start_time) expect(ice_cube_start_time.utc_offset).to eq(start_time.utc_offset) end it 'should be able to roll forward times and get back times in an array - Time' do start_time = Time.now schedule = Schedule.new(start_time) schedule = Schedule.from_yaml(schedule.to_yaml) # round trip ice_cube_start_time = schedule.start_time expect(ice_cube_start_time.to_s).to eq(start_time.to_s) expect(ice_cube_start_time.class).to eq(Time) expect(ice_cube_start_time.utc_offset).to eq(start_time.utc_offset) end it 'should be able to go back and forth to yaml and then call occurrences' do start_time = Time.local(2011, 5, 10, 12, 0, 0) schedule1 = Schedule.new(start_time) schedule1.add_recurrence_time start_time schedule2 = Schedule.from_yaml(schedule1.to_yaml) # round trip end_time = Time.now + ONE_DAY expect(schedule1.occurrences(end_time)).to eq(schedule2.occurrences(end_time)) end it 'should be able to make a round trip with an exception time' do schedule = Schedule.new schedule.add_exception_time(time = Time.now) schedule = Schedule.from_yaml schedule.to_yaml expect(schedule.extimes.map(&:to_s)).to eq([time.to_s]) end it 'crazy shit' do start_time = Time.zone.now schedule = Schedule.new(start_time) schedule.add_recurrence_rule Rule.weekly.day(:wednesday) schedule.add_recurrence_time start_time schedule = Schedule.from_hash(schedule.to_hash) schedule = Schedule.from_yaml(schedule.to_yaml) schedule.occurrences(start_time + ONE_DAY * 14) end it 'should be able to make a round trip to hash with a duration' do schedule = Schedule.new Time.now, :duration => 3600 expect(Schedule.from_hash(schedule.to_hash).duration).to eq(3600) end it 'should be able to be serialized to yaml as part of a hash' do schedule = Schedule.new Time.now hash = { :schedule => schedule } expect do hash.to_yaml end.not_to raise_error end it 'should be able to roll forward and back in time' do schedule = Schedule.new(Time.now) rt_schedule = Schedule.from_yaml(schedule.to_yaml) expect(rt_schedule.start_time.utc_offset).to eq(schedule.start_time.utc_offset) end it 'should be backward compatible with old yaml Time format', expect_warnings: true do pacific_time = 'Pacific Time (US & Canada)' yaml = "---\n:end_time:\n:rdates: []\n:rrules: []\n:duration:\n:exdates: []\n:start_time: 2010-10-18T14:35:47-07:00" schedule = Schedule.from_yaml(yaml) expect(schedule.start_time).to be_a(Time) end it 'should work to_yaml with non-TimeWithZone' do schedule = Schedule.new(Time.now) expect(schedule.to_yaml.length).to be < 200 end it 'should work with occurs_on and TimeWithZone' do pacific_time = 'Pacific Time (US & Canada)' Time.zone = pacific_time schedule = Schedule.new(Time.zone.now) schedule.add_recurrence_rule Rule.weekly expect(schedule.occurs_on?(schedule.start_time.to_date + 6)).to be_falsey expect(schedule.occurs_on?(schedule.start_time.to_date + 7)).to be_truthy expect(schedule.occurs_on?(schedule.start_time.to_date + 8)).to be_falsey end it 'should work with occurs_on and TimeWithZone' do start_time = Time.zone.local(2012, 7, 15, 12, 0, 0) pacific_time = 'Pacific Time (US & Canada)' Time.zone = pacific_time schedule = Schedule.new(start_time) schedule.add_recurrence_time start_time + 7 * ONE_DAY expect(schedule.occurs_on?(schedule.start_time.to_date + 6)).to be_falsey expect(schedule.occurs_on?(schedule.start_time.to_date + 7)).to be_truthy expect(schedule.occurs_on?(schedule.start_time.to_date + 8)).to be_falsey end it 'should crazy patch' do Time.zone = 'Pacific Time (US & Canada)' day = Time.zone.parse('21 Oct 2010 02:00:00') schedule = Schedule.new(day) schedule.add_recurrence_time(day) expect(schedule.occurs_on?(Date.new(2010, 10, 20))).to be_falsey expect(schedule.occurs_on?(Date.new(2010, 10, 21))).to be_truthy expect(schedule.occurs_on?(Date.new(2010, 10, 22))).to be_falsey end it 'should be able to bring a Rule to_yaml and back with a timezone' do Time.zone = 'Pacific Time (US & Canada)' time = Time.now offset = time.utc_offset rule = Rule.daily.until(time) rule = Rule.from_yaml(rule.to_yaml) expect(rule.until_time.utc_offset).to eq(offset) end it 'should be able to bring a Rule to_yaml and back with a count' do rule = Rule.daily.count(5) rule = Rule.from_yaml rule.to_yaml expect(rule.occurrence_count).to eq(5) end it 'should be able to bring a Rule to_yaml and back with an undefined week start' do rule = Rule.weekly(2) rule = Rule.from_yaml rule.to_yaml expect(rule.week_start).to eq(:sunday) end it 'should be able to bring a Rule to_yaml and back with a week start defined' do rule = Rule.weekly.interval(2, :monday) rule = Rule.from_yaml rule.to_yaml expect(rule.week_start).to eq(:monday) end it 'should be able to bring in a schedule with a rule from hash with symbols or strings' do time = Time.zone.now symbol_data = { :start_time => time, :rrules => [ { :validations => { :day => [1] }, :rule_type => "IceCube::DailyRule", :interval => 1 } ], :rtimes => [], :extimes => [] } string_data = { 'start_time' => time, 'rrules' => [ { 'validations' => { 'day' => [1] }, 'rule_type' => "IceCube::DailyRule", 'interval' => 1 } ], 'rtimes' => [], 'extimes' => [] } symbol_yaml = Schedule.from_hash(symbol_data).to_yaml string_yaml = Schedule.from_hash(string_data).to_yaml expect(YAML.load(symbol_yaml)).to eq(YAML.load(string_yaml)) end it 'should raise an ArgumentError when trying to deserialize an invalid rule type' do data = {:rule_type => 'IceCube::FakeRule', :interval => 1} expect { Rule.from_hash(data) }.to raise_error(ArgumentError, 'Invalid rule frequency type: Fake') end it 'should raise an ArgumentError when trying to deserialize an invalid validation' do data = {:validations => {:fake => []}, :rule_type => 'IceCube::DailyRule', :interval => 1} expect { Rule.from_hash(data) }.to raise_error(ArgumentError, 'Invalid rule validation type: fake') end end end
Promptus/ice_cube
lib/ice_cube/single_occurrence_rule.rb
<reponame>Promptus/ice_cube module IceCube class SingleOccurrenceRule < Rule attr_reader :time def initialize(time) @time = TimeUtil.ensure_time time end # Always terminating def terminating? true end def next_time(t, _, closing_time) unless closing_time && closing_time < t time if time.to_i >= t.to_i end end def to_hash { :time => time } end end end
Promptus/ice_cube
spec/examples/rfc_spec.rb
require File.dirname(__FILE__) + '/../spec_helper' describe IceCube::Schedule do it 'should ~ daily for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(2010, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.daily.count(10) test_expectations(schedule, {2010 => {9 => [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]}}) end it 'should ~ daily until a certain date' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.daily.until(Time.utc(1997, 12, 24)) dates = schedule.all_occurrences expectation = (Date.civil(1997, 9, 2)..Date.civil(1997, 12, 24)).to_a expectation = expectation.map { |d| Time.utc(d.year, d.month, d.day) } expect(dates).to eq(expectation) end it 'should ~ every other day' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.daily(2).until(Time.utc(1997, 12, 24)) dates = schedule.occurrences(Time.utc(1997, 12, 31)) offset = 0 (Date.new(1997, 9, 2)..Date.new(1997, 12, 24)).each do |date| expect(dates).to include(Time.utc(date.year, date.month, date.day)) if offset % 2 == 0 expect(dates).not_to include(Time.utc(date.year, date.month, date.day)) if offset % 2 != 0 offset += 1 end end it 'should ~ interval 10, count 5' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.daily(10).count(5) dates = schedule.occurrences(Time.utc(1998, 1, 1)) expect(dates).to eq([Time.utc(1997, 9, 2), Time.utc(1997, 9, 12), Time.utc(1997, 9, 22), Time.utc(1997, 10, 2), Time.utc(1997, 10, 12)]) end it 'should ~ everyday in january, for 3 years (a)' do schedule = IceCube::Schedule.new(Time.utc(1998, 1, 1)) schedule.add_recurrence_rule IceCube::Rule.yearly.until(Time.utc(2000, 1, 31)).month_of_year(:january).day(:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday) dates = schedule.occurrences(Time.utc(2000, 1, 31)) dates.each do |date| expect(date.month).to eq(1) expect([1998, 1999, 2000]).to include(date.year) end end it 'should ~ everyday in january, for 3 years (b)' do schedule = IceCube::Schedule.new(Time.utc(1998, 1, 1)) schedule.add_recurrence_rule IceCube::Rule.daily.month_of_year(:january).until(Time.utc(2000, 1, 31)) dates = schedule.occurrences(Time.utc(2000, 1, 31)) dates.each do |date| expect(date.month).to eq(1) expect([1998, 1999, 2000]).to include(date.year) end end it 'should ~ weekly for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.weekly.count(10) dates = schedule.occurrences(Time.utc(2000, 1, 1)) expect(dates).to eq([Time.utc(1997, 9, 2), Time.utc(1997, 9, 9), Time.utc(1997, 9, 16), Time.utc(1997, 9, 23), Time.utc(1997, 9, 30), Time.utc(1997, 10, 7), Time.utc(1997, 10, 14), Time.utc(1997, 10, 21), Time.utc(1997, 10, 28), Time.utc(1997, 11, 4)]) end it 'should ~ weekly until december 24, 1997' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.weekly.until(Time.utc(1997, 12, 24)) dates = schedule.occurrences(Time.utc(1997, 12, 24)) #test expectations test_expectations(schedule, {1997 => {9 => [2, 9, 16, 23, 30], 10 => [7, 14, 21, 28], 11 => [4, 11, 18, 25], 12 => [2, 9, 16, 23]}}) end it 'should ~ every other week' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.weekly(2) dates = schedule.occurrences(Time.utc(1997, 12, 31)) #check assumption previous_date = dates.shift dates.each do |date| expect(date.yday).to eq(previous_date.yday + 14) previous_date = date end end # it 'should ~ weekly on tuesday and thursday for 5 weeks (a)' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.weekly.until(Time.utc(1997, 10, 6)).day(:tuesday, :thursday) dates = schedule.occurrences(Time.utc(1997, 12, 1)) expectation = [] expectation << [2, 4, 9, 11, 16, 18, 23, 25, 30].map { |d| Time.utc(1997, 9, d) } expectation << [2].map { |d| Time.utc(1997, 10, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ weekly on tuesday and thursday for 5 weeks (b)' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.weekly.day(:tuesday, :thursday).count(10) dates = schedule.occurrences(Time.utc(1997, 12, 1)) expectation = [] expectation << [2, 4, 9, 11, 16, 18, 23, 25, 30].map { |d| Time.utc(1997, 9, d) } expectation << [2].map { |d| Time.utc(1997, 10, d) } expect(dates).to eq(expectation.flatten) end # it 'should ~ every other week on monday, wednesday and friday until december 24, 1997 but starting on tuesday september 2, 1997' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.weekly(2).until(Time.utc(1997, 12, 24)).day(:monday, :wednesday, :friday) dates = schedule.occurrences(Time.utc(1997, 12, 24)) expectation = [] expectation << [3, 5, 15, 17, 19, 29].map { |d| Time.utc(1997, 9, d) } expectation << [1, 3, 13, 15, 17, 27, 29, 31].map { |d| Time.utc(1997, 10, d) } expectation << [10, 12, 14, 24, 26, 28].map { |d| Time.utc(1997, 11, d) } expectation << [8, 10, 12, 22, 24].map { |d| Time.utc(1997, 12, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ every other week on tuesday and thursday for 8 occurrences' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.weekly(2).day(:tuesday, :thursday).count(8) dates = schedule.occurrences(Time.utc(1997, 11, 1)) expectation = [] expectation << [2, 4, 16, 18, 30].map { |d| Time.utc(1997, 9, d) } expectation << [2, 14, 16].map { |d| Time.utc(1997, 10, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ monthly on the 1st friday for ten occurrences' do start_time = Time.utc(1997, 9, 5) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.day_of_week(:friday => [1]).count(10) dates = schedule.occurrences(Time.utc(1998, 7, 1)) expectation = [Time.utc(1997, 9, 5), Time.utc(1997, 10, 3), Time.utc(1997, 11, 7), Time.utc(1997, 12, 5), Time.utc(1998, 1, 2), Time.utc(1998, 2, 6), Time.utc(1998, 3, 6), Time.utc(1998, 4, 3), Time.utc(1998, 5, 1), Time.utc(1998, 6, 5)] expect(dates).to eq(expectation) end it 'should ~ monthly on the first friday until december 24, 1997' do start_time = Time.utc(1997, 9, 5) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.until(Time.utc(1997, 12, 24)).day_of_week(:friday => [1]) dates = schedule.occurrences(Time.utc(1998, 12, 24)) expectation = [Time.utc(1997, 9, 5), Time.utc(1997, 10, 3), Time.utc(1997, 11, 7), Time.utc(1997, 12, 5)] expect(dates).to eq(expectation) end it 'should ~ every other month on the 1st and last sunday of the month for 10 occurrences' do start_time = Time.utc(1997, 9, 7) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly(2).day_of_week(:sunday => [1, -1]).count(10) dates = schedule.occurrences(Time.utc(1998, 12, 1)) expectation = [Time.utc(1997, 9, 7), Time.utc(1997, 9, 28), Time.utc(1997, 11, 2), Time.utc(1997, 11, 30), Time.utc(1998, 1, 4), Time.utc(1998, 1, 25), Time.utc(1998, 3, 1), Time.utc(1998, 3, 29), Time.utc(1998, 5, 3), Time.utc(1998, 5, 31)] expect(dates).to eq(expectation) end it 'should ~ monthly on the second to last monday of the month for 6 months' do start_time = Time.utc(1997, 9, 22) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.day_of_week(:monday => [-2]).count(6) dates = schedule.occurrences(Time.utc(1998, 3, 1)) expectation = [Time.utc(1997, 9, 22), Time.utc(1997, 10, 20), Time.utc(1997, 11, 17), Time.utc(1997, 12, 22), Time.utc(1998, 1, 19), Time.utc(1998, 2, 16)] expect(dates).to eq(expectation) end it 'should ~ monthly on the third to last day of the month, 6 times' do start_time = Time.utc(1997, 9, 28) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.day_of_month(-3).count(6) dates = schedule.occurrences(Time.utc(1998, 2, 26)) expectation = [Time.utc(1997, 9, 28), Time.utc(1997, 10, 29), Time.utc(1997, 11, 28), Time.utc(1997, 12, 29), Time.utc(1998, 1, 29), Time.utc(1998, 2, 26)] expect(dates).to eq(expectation) end it 'should ~ monthly on the 2nd and 15th of the month for 10 occurrences' do start_time = Time.utc(1997, 9, 2) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.day_of_month(2, 15).count(10) dates = schedule.occurrences(Time.utc(1998, 1, 16)) expectation = [Time.utc(1997, 9, 2), Time.utc(1997, 9, 15), Time.utc(1997, 10, 2), Time.utc(1997, 10, 15), Time.utc(1997, 11, 2), Time.utc(1997, 11, 15), Time.utc(1997, 12, 2), Time.utc(1997, 12, 15), Time.utc(1998, 1, 2), Time.utc(1998, 1, 15)] expect(dates).to eq(expectation) end it 'should ~ monthly on the 1st and last days of the month for 10 occurrences' do start_time = Time.utc(1997, 9, 30) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.monthly.day_of_month(1, -1).count(10) dates = schedule.occurrences(Time.utc(1998, 2, 2)) expectation = [Time.utc(1997, 9, 30), Time.utc(1997, 10, 1), Time.utc(1997, 10, 31), Time.utc(1997, 11, 1), Time.utc(1997, 11, 30), Time.utc(1997, 12, 1), Time.utc(1997, 12, 31), Time.utc(1998, 1, 1), Time.utc(1998, 1, 31), Time.utc(1998, 2, 1)] expect(dates).to eq(expectation) end it 'should ~ every 18 months on the 10th through the 15th of the month for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 10)) schedule.add_recurrence_rule IceCube::Rule.monthly(18).day_of_month(10, 11, 12, 13, 14, 15).count(10) dates = schedule.occurrences(Time.utc(1999, 12, 1)) expectation = [] expectation << [10, 11, 12, 13, 14, 15].map { |d| Time.utc(1997, 9, d) } expectation << [10, 11, 12, 13].map { |d| Time.utc(1999, 3, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ every tuesday, every other month' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.monthly(2).day(:tuesday) dates = schedule.occurrences(Time.utc(1998, 4, 1)) expectation = [] expectation << [2, 9, 16, 23, 30].map { |d| Time.utc(1997, 9, d) } expectation << [4, 11, 18, 25].map { |d| Time.utc(1997, 11, d) } expectation << [6, 13, 20, 27].map { |d| Time.utc(1998, 1, d) } expectation << [3, 10, 17, 24, 31].map { |d| Time.utc(1998, 3, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ yearly in june and july for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(1997, 6, 10)) schedule.add_recurrence_rule IceCube::Rule.yearly.month_of_year(:june, :july).count(10) dates = schedule.occurrences(Time.utc(2001, 8, 1)) expectation = [] (1997..2001).each do |year| expectation << Time.utc(year, 6, 10) expectation << Time.utc(year, 7, 10) end expect(dates).to eq(expectation.flatten) end it 'should ~ every other year on january, feburary, and march for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(1997, 3, 10)) schedule.add_recurrence_rule IceCube::Rule.yearly(2).month_of_year(:january, :february, :march).count(10) dates = schedule.occurrences(Time.utc(2003, 4, 1)) expectation = [Time.utc(1997, 3, 10), Time.utc(1999, 1, 10), Time.utc(1999, 2, 10), Time.utc(1999, 3, 10), Time.utc(2001, 1, 10), Time.utc(2001, 2, 10), Time.utc(2001, 3, 10), Time.utc(2003, 1, 10), Time.utc(2003, 2, 10), Time.utc(2003, 3, 10)] expect(dates).to eq(expectation) end it 'should ~ every third year on the 1st, 100th and 200th day for 10 occurrences' do schedule = IceCube::Schedule.new(Time.utc(1997, 1, 1)) schedule.add_recurrence_rule IceCube::Rule.yearly(3).day_of_year(1, 100, 200).count(10) dates = schedule.occurrences(Time.utc(2006, 1, 2)) expectation = [Time.utc(1997, 1, 1), Time.utc(1997, 4, 10), Time.utc(1997, 7, 19), Time.utc(2000, 1, 1), Time.utc(2000, 4, 9), Time.utc(2000, 7, 18), Time.utc(2003, 1, 1), Time.utc(2003, 4, 10), Time.utc(2003, 7, 19), Time.utc(2006, 1, 1)] expect(dates).to eq(expectation) end it 'should ~ every thursday in march, forever' do schedule = IceCube::Schedule.new(Time.utc(1997, 3, 13)) schedule.add_recurrence_rule IceCube::Rule.yearly.month_of_year(:march).day(:thursday) dates = schedule.occurrences(Time.utc(1999, 3, 25)) expectation = [] expectation << [13, 20, 27].map { |d| Time.utc(1997, 3, d) } expectation << [5, 12, 19, 26].map { |d| Time.utc(1998, 3, d) } expectation << [4, 11, 18, 25].map { |d| Time.utc(1999, 3, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ every thursday, but only during june, july, and august' do schedule = IceCube::Schedule.new(Time.utc(1997, 6, 5)) schedule.add_recurrence_rule IceCube::Rule.yearly.day(:thursday).month_of_year(:june, :july, :august) dates = schedule.occurrences(Time.utc(1998, 9, 1)) expectation = [] expectation << [5, 12, 19, 26].map { |d| Time.utc(1997, 6, d) } expectation << [3, 10, 17, 24, 31].map { |d| Time.utc(1997, 7, d) } expectation << [7, 14, 21, 28].map { |d| Time.utc(1997, 8, d) } expectation << [4, 11, 18, 25].map { |d| Time.utc(1998, 6, d) } expectation << [2, 9, 16, 23, 30].map { |d| Time.utc(1998, 7, d) } expectation << [6, 13, 20, 27].map { |d| Time.utc(1998, 8, d) } expect(dates).to eq(expectation.flatten) end it 'should ~ every friday the 13th' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 2)) schedule.add_recurrence_rule IceCube::Rule.monthly.day(:friday).day_of_month(13) dates = schedule.occurrences(Time.utc(2000, 10, 13)) expectation = [Time.utc(1998, 2, 13), Time.utc(1998, 3, 13), Time.utc(1998, 11, 13), Time.utc(1999, 8, 13), Time.utc(2000, 10, 13)] expect(dates).to eq(expectation) end it 'should ~ the first saturday that follows the first sunday of the month' do schedule = IceCube::Schedule.new(Time.utc(1997, 9, 13)) schedule.add_recurrence_rule IceCube::Rule.monthly.day(:saturday).day_of_month(7, 8, 9, 10, 11, 12, 13) dates = schedule.occurrences(Time.utc(1997, 12, 13)) expectation = [Time.utc(1997, 9, 13), Time.utc(1997, 10, 11), Time.utc(1997, 11, 8), Time.utc(1997, 12, 13)] expect(dates).to eq(expectation) end it 'should ~ every 4 years, the first tuesday after a monday in november (u.s. presidential election day)' do schedule = IceCube::Schedule.new(Time.utc(1996, 11, 5)) schedule.add_recurrence_rule IceCube::Rule.yearly(4).month_of_year(:november).day(:tuesday).day_of_month(2, 3, 4, 5, 6, 7, 8) dates = schedule.occurrences(Time.utc(2004, 11, 2)) expectation = [Time.utc(1996, 11, 5), Time.utc(2000, 11, 7), Time.utc(2004, 11, 2)] expect(dates).to eq(expectation) end it 'should ~ every 3 hours from 9am to 5pm on a specific day' do start_time = Time.utc(1997, 9, 2, 9, 0, 0) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.hourly(3).until(Time.utc(1997, 9, 2, 17, 0, 0)) dates = schedule.all_occurrences expect(dates).to eq([Time.utc(1997, 9, 2, 9, 0, 0), Time.utc(1997, 9, 2, 12, 0, 0), Time.utc(1997, 9, 2, 15, 0, 0)]) end it 'should ~ every 15 minutes for 6 occurrences' do start_time = Time.utc(1997, 9, 2, 9, 0, 0) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.minutely(15).count(6) dates = schedule.all_occurrences expect(dates).to eq([Time.utc(1997, 9, 2, 9, 0, 0), Time.utc(1997, 9, 2, 9, 15, 0), Time.utc(1997, 9, 2, 9, 30, 0), Time.utc(1997, 9, 2, 9, 45, 0), Time.utc(1997, 9, 2, 10, 0, 0), Time.utc(1997, 9, 2, 10, 15, 0)]) end it 'should ~ every hour and a half for 4 occurrences' do start_time = Time.utc(1997, 9, 2, 9, 0, 0) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.minutely(90).count(4) dates = schedule.all_occurrences expect(dates).to eq([Time.utc(1997, 9, 2, 9, 0, 0), Time.utc(1997, 9, 2, 10, 30, 0), Time.utc(1997, 9, 2, 12, 0, 0), Time.utc(1997, 9, 2, 13, 30, 0)]) end it 'should ~ every 20 minutes from 9am to 4:40pm every day (a)' do start_time = Time.utc(1997, 9, 2, 8, 0, 0) end_date = Time.utc(1997, 9, 2, 10, 20, 0) schedule = IceCube::Schedule.new(start_time) schedule.add_recurrence_rule IceCube::Rule.daily.hour_of_day(9, 10, 11, 12, 13, 14, 15, 16).minute_of_hour(0, 20, 40).until(end_date) dates = schedule.all_occurrences expecation = [Time.utc(1997, 9, 2, 9), Time.utc(1997, 9, 2, 9, 20), Time.utc(1997, 9, 2, 9, 40), Time.utc(1997, 9, 2, 10, 0), Time.utc(1997, 9, 2, 10, 20)] expect(dates).to eq(expecation) end end def test_expectations(schedule, dates_array) expectation = [] dates_array.each do |y, months| months.each do |m, days| days.each do |d| expectation << Time.utc(y, m, d) end end end # test equality expectation.sort! expect(schedule.occurrences(expectation.last)).to eq(expectation) expectation.each do |date| expect(schedule).to be_occurs_at(date) end end
Promptus/ice_cube
lib/ice_cube/validations/daily_interval.rb
module IceCube module Validations::DailyInterval # Add a new interval validation def interval(interval) @interval = normalized_interval(interval) replace_validations_for(:interval, [Validation.new(@interval)]) clobber_base_validations(:wday, :day) self end class Validation attr_reader :interval def initialize(interval) @interval = interval end def type :day end def dst_adjust? true end def validate(step_time, start_time) t0, t1 = start_time, step_time days = Date.new(t1.year, t1.month, t1.day) - Date.new(t0.year, t0.month, t0.day) offset = (days % interval).nonzero? interval - offset if offset end def build_s(builder) builder.base = IceCube::I18n.t('ice_cube.each_day', count: interval) end def build_hash(builder) builder[:interval] = interval end def build_ical(builder) builder['FREQ'] << 'DAILY' builder['INTERVAL'] << interval unless interval == 1 end end end end
Promptus/ice_cube
lib/ice_cube/version.rb
module IceCube VERSION = '0.16.1' end
nagatea/traQ_webhook-ruby
lib/traq_webhook.rb
require "traq_webhook/version" require "net/http" require "uri" require "openssl" module TraqWebhook class Client attr_accessor :id, :token, :channel_id def initialize yield self if block_given? end def post(message) signature = calc_hmacsha1(self.token, message) uri = URI.parse('https://q.trap.jp/api/1.0/webhooks/' + self.id) req = Net::HTTP::Post.new(uri.path) req['Content-Type'] = 'text/plain; charset=utf-8' req['X-TRAQ-Signature'] = signature req['X-TRAQ-Channel-Id'] = self.channel_id unless self.channel_id.nil? req.body = message option = { use_ssl: uri.scheme = "https" } res = Net::HTTP.start(uri.hostname, uri.port, option) do |http| http.request(req) end end private def calc_hmacsha1(token, body) OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), token, body) end end end
mislav/twitter
lib/twitter/metadata.rb
require 'twitter/base' module Twitter class Metadata < Twitter::Base lazy_attr_reader :result_type end end
mislav/twitter
spec/twitter/client/trends_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#trends_daily" do before do stub_get("/1/trends/daily.json"). with(:query => {:date => "2010-10-24"}). to_return(:body => fixture("trends_daily.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.trends_daily(Date.parse("2010-10-24")) a_get("/1/trends/daily.json"). with(:query => {:date => "2010-10-24"}). should have_been_made end it "should return the top 20 trending topics for each hour in a given day" do trends = @client.trends_daily(Date.parse("2010-10-24")) trends.should be_a Hash trends["2010-10-24 17:00"].should be_an Array trends["2010-10-24 17:00"].first.should be_a Twitter::Trend trends["2010-10-24 17:00"].first.name.should == "#bigbangcomeback" end end describe "#trends_weekly" do before do stub_get("/1/trends/weekly.json"). with(:query => {:date => "2010-10-24"}). to_return(:body => fixture("trends_weekly.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.trends_weekly(Date.parse("2010-10-24")) a_get("/1/trends/weekly.json"). with(:query => {:date => "2010-10-24"}). should have_been_made end it "should return the top 30 trending topics for each day in a given week" do trends = @client.trends_weekly(Date.parse("2010-10-24")) trends.should be_a Hash trends["2010-10-24"].should be_an Array trends["2010-10-24"].first.should be_a Twitter::Trend trends["2010-10-24"].first.name.should == "#youcantbeuglyand" end end end
mislav/twitter
spec/twitter/client/users_spec.rb
<filename>spec/twitter/client/users_spec.rb require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#users" do context "with screen names passed" do before do stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.users("sferik", "pengwynn") a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made end it "should return up to 100 users worth of extended information" do users = @client.users("sferik", "pengwynn") users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end context "with numeric screen names passed" do before do stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "0,311"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.users("0", "311") a_get("/1/users/lookup.json"). with(:query => {:screen_name => "0,311"}). should have_been_made end end context "with user IDs passed" do before do stub_get("/1/users/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.users(7505382, 14100886) a_get("/1/users/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). should have_been_made end end context "with both screen names and user IDs passed" do before do stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.users("sferik", 14100886) a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). should have_been_made end end context "with user objects passed" do context "with user IDs" do before do stub_get("/1/users/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('id' => '7505382') user2 = Twitter::User.new('id' => '14100886') @client.users(user1, user2) a_get("/1/users/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). should have_been_made end end context "with screen_names IDs" do before do stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('screen_name' => 'sferik') user2 = Twitter::User.new('screen_name' => 'pengwynn') @client.users(user1, user2) a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made end end context "with both screen names and user IDs" do before do stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). to_return(:body => fixture("users.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('screen_name' => 'sferik') user2 = Twitter::User.new('id' => '14100886') @client.users(user1, user2) a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). should have_been_made end end end end describe "#profile_image" do context "with a screen name passed" do before do stub_get("/1/users/profile_image/sferik"). to_return(fixture("profile_image.text")) end it "should redirect to the correct resource" do profile_image = @client.profile_image("sferik") a_get("/1/users/profile_image/sferik"). with(:status => 302). should have_been_made profile_image.should == "http://a0.twimg.com/profile_images/323331048/me_normal.jpg" end end context "without a screen name passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/profile_image/sferik"). to_return(fixture("profile_image.text")) end it "should redirect to the correct resource" do profile_image = @client.profile_image a_get("/1/users/profile_image/sferik"). with(:status => 302). should have_been_made profile_image.should == "http://a0.twimg.com/profile_images/323331048/me_normal.jpg" end end context "with a user object passed" do before do stub_get("/1/users/profile_image/sferik"). to_return(fixture("profile_image.text")) end it "should redirect to the correct resource" do user = Twitter::User.new('screen_name' => 'sferik') profile_image = @client.profile_image(user) a_get("/1/users/profile_image/sferik"). with(:status => 302). should have_been_made profile_image.should == "http://a0.twimg.com/profile_images/323331048/me_normal.jpg" end end end describe "#user_search" do before do stub_get("/1/users/search.json"). with(:query => {:q => "<NAME>"}). to_return(:body => fixture("user_search.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user_search("<NAME>") a_get("/1/users/search.json"). with(:query => {:q => "<NAME>"}). should have_been_made end it "should return an array of user search results" do user_search = @client.user_search("<NAME>") user_search.should be_an Array user_search.first.should be_a Twitter::User user_search.first.name.should == "<NAME>" end end describe "#user" do context "with a screen name passed" do before do stub_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user("sferik") a_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return extended information of a given user" do user = @client.user("sferik") user.should be_a Twitter::User user.name.should == "<NAME>" end end context "with a screen name including '@' passed" do before do stub_get("/1/users/show.json"). with(:query => {:screen_name => "@sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user("@sferik") a_get("/1/users/show.json"). with(:query => {:screen_name => "@sferik"}). should have_been_made end end context "with a numeric screen name passed" do before do stub_get("/1/users/show.json"). with(:query => {:screen_name => "0"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user("0") a_get("/1/users/show.json"). with(:query => {:screen_name => "0"}). should have_been_made end end context "with a user ID passed" do before do stub_get("/1/users/show.json"). with(:query => {:user_id => "7505382"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user(7505382) a_get("/1/users/show.json"). with(:query => {:user_id => "7505382"}). should have_been_made end end context "with a user object passed" do context "with a user ID" do before do stub_get("/1/users/show.json"). with(:query => {:user_id => "7505382"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user = Twitter::User.new('id' => 7505382) @client.user(user) a_get("/1/users/show.json"). with(:query => {:user_id => "7505382"}). should have_been_made end end context "with a screen_name" do before do stub_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user = Twitter::User.new('screen_name' => 'sferik') @client.user(user) a_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end end end context "without a screen name or user ID passed" 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.user a_get("/1/account/verify_credentials.json"). should have_been_made end end end describe "#user?" do before do stub_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/show.json"). with(:query => {:screen_name => "pengwynn"}). to_return(:body => fixture("not_found.json"), :status => 404, :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user?("sferik") a_get("/1/users/show.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return true if user exists" do user = @client.user?("sferik") user.should be_true end it "should return false if user does not exist" do user = @client.user?("pengwynn") user.should be_false end end describe "#contributees" do context "with a screen name passed" do before do stub_get("/1/users/contributees.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("contributees.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.contributees("sferik") a_get("/1/users/contributees.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return a user's contributees" do contributees = @client.contributees("sferik") contributees.should be_an Array contributees.first.should be_a Twitter::User contributees.first.name.should == "Twitter API" end end context "without arguments passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/contributees.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("contributees.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.contributees a_get("/1/users/contributees.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return a user's contributees" do contributees = @client.contributees contributees.should be_an Array contributees.first.should be_a Twitter::User contributees.first.name.should == "Twitter API" end end end describe "#contributors" do context "with a screen name passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/contributors.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("contributors.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.contributors("sferik") a_get("/1/users/contributors.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return a user's contributors" do contributors = @client.contributors("sferik") contributors.should be_an Array contributors.first.should be_a Twitter::User contributors.first.name.should == "<NAME>" end end context "without arguments passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/contributors.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("contributors.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.contributors a_get("/1/users/contributors.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return a user's contributors" do contributors = @client.contributors contributors.should be_an Array contributors.first.should be_a Twitter::User contributors.first.name.should == "<NAME>" end end end describe "#recommendations" do context "with a screen name passed" do before do stub_get("/1/users/recommendations.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("recommendations.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.recommendations("sferik") a_get("/1/users/recommendations.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return recommended users for the authenticated user" do recommendations = @client.recommendations("sferik") recommendations.should be_an Array recommendations.first.should be_a Twitter::User recommendations.first.name.should == "<NAME>" end end context "without arguments passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/recommendations.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("recommendations.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.recommendations a_get("/1/account/verify_credentials.json"). should have_been_made a_get("/1/users/recommendations.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return recommended users for the authenticated user" do recommendations = @client.recommendations recommendations.should be_an Array recommendations.first.should be_a Twitter::User recommendations.first.name.should == "<NAME>" end end end describe "#following_followers_of" do context "with a screen_name passed" do before do stub_get("/users/following_followers_of.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). to_return(:body => fixture("users_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.following_followers_of("sferik") a_get("/users/following_followers_of.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). should have_been_made end it "should return an array of numeric IDs for every user following the specified user" do following_followers_of = @client.following_followers_of("sferik") following_followers_of.should be_a Twitter::Cursor following_followers_of.users.should be_an Array following_followers_of.users.first.should be_a Twitter::User end end context "without arguments passed" do before do stub_get("/1/account/verify_credentials.json"). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/users/following_followers_of.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). to_return(:body => fixture("users_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.following_followers_of a_get("/1/account/verify_credentials.json"). should have_been_made a_get("/users/following_followers_of.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). should have_been_made end it "should return an array of numeric IDs for every user following the specified user" do following_followers_of = @client.following_followers_of following_followers_of.should be_a Twitter::Cursor following_followers_of.users.should be_an Array following_followers_of.users.first.should be_a Twitter::User end end end end
mislav/twitter
lib/twitter/error/service_unavailable.rb
require 'twitter/error/server_error' module Twitter # Raised when Twitter returns the HTTP status code 503 class Error::ServiceUnavailable < Twitter::Error::ServerError end end
mislav/twitter
lib/twitter/search_results.rb
require 'twitter/base' module Twitter class SearchResults < Twitter::Base lazy_attr_reader :completed_in, :max_id, :next_page, :page, :query, :refresh_url, :results_per_page, :since_id # @return [Array<Twitter::Status>] def results @results ||= Array(@attrs['results']).map{|status| Twitter::Status.new(status)} end alias :collection :results end end
mislav/twitter
lib/twitter/error/internal_server_error.rb
require 'twitter/error/server_error' module Twitter # Raised when Twitter returns the HTTP status code 500 class Error::InternalServerError < Twitter::Error::ServerError end end
mislav/twitter
spec/twitter/point_spec.rb
<reponame>mislav/twitter require 'helper' describe Twitter::Point do before do @point = Twitter::Point.new('coordinates' => [-122.399983, 37.788299]) end describe "#==" do it "should return true when coordinates are equal" do other = Twitter::Point.new('coordinates' => [-122.399983, 37.788299]) (@point == other).should be_true end it "should return false when coordinates are not equal" do other = Twitter::Point.new('coordinates' => [37.788299, -122.399983]) (@point == other).should be_false end end describe "#latitude" do it "should return the latitude" do @point.latitude.should == -122.399983 end end describe "#longitude" do it "should return the longitude" do @point.longitude.should == 37.788299 end end end
mislav/twitter
spec/twitter/relationship_spec.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'helper' describe Twitter::Relationship do describe "#source" do it "should return a User when source is set" do source = Twitter::Relationship.new('source' => {}).source source.should be_a Twitter::User end it "should return nil when source is not set" do source = Twitter::Relationship.new.source source.should be_nil end end describe "#target" do it "should return a User when target is set" do target = Twitter::Relationship.new('target' => {}).target target.should be_a Twitter::User end it "should return nil when target is not set" do target = Twitter::Relationship.new.target target.should be_nil end end end
mislav/twitter
lib/twitter/error/forbidden.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 403 class Error::Forbidden < Twitter::Error::ClientError end end
mislav/twitter
spec/twitter/client/timelines_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#home_timeline" do before do stub_get("/1/statuses/home_timeline.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.home_timeline a_get("/1/statuses/home_timeline.json"). should have_been_made end it "should return the 20 most recent statuses, including retweets if they exist, posted by the authenticating user and the user's they follow" do statuses = @client.home_timeline statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end describe "#mentions" do before do stub_get("/1/statuses/mentions.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.mentions a_get("/1/statuses/mentions.json"). should have_been_made end it "should return the 20 most recent mentions (status containing @username) for the authenticating user" do statuses = @client.mentions statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end describe "#retweeted_by" do context "with a screen name passed" do before do stub_get("/1/statuses/retweeted_by_user.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeted_by("sferik") a_get("/1/statuses/retweeted_by_user.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return the 20 most recent retweets posted by the authenticating user" do statuses = @client.retweeted_by("sferik") statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end context "without a screen name passed" do before do stub_get("/1/statuses/retweeted_by_me.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeted_by a_get("/1/statuses/retweeted_by_me.json"). should have_been_made end end end describe "#retweeted_to" do context "with a screen name passed" do before do stub_get("/1/statuses/retweeted_to_user.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeted_to("sferik") a_get("/1/statuses/retweeted_to_user.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return the 20 most recent retweets posted by users the authenticating user follow" do statuses = @client.retweeted_to("sferik") statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end context "without a screen name passed" do before do stub_get("/1/statuses/retweeted_to_me.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweeted_to a_get("/1/statuses/retweeted_to_me.json"). should have_been_made end end end describe "#retweets_of_me" do before do stub_get("/1/statuses/retweets_of_me.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.retweets_of_me a_get("/1/statuses/retweets_of_me.json"). should have_been_made end it "should return the 20 most recent tweets of the authenticated user that have been retweeted by others" do statuses = @client.retweets_of_me statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end describe "#user_timeline" do context "with a screen name passed" do before do stub_get("/1/statuses/user_timeline.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user_timeline("sferik") a_get("/1/statuses/user_timeline.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return the 20 most recent statuses posted by the user specified by screen name or user id" do statuses = @client.user_timeline("sferik") statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end context "without a screen name passed" do before do stub_get("/1/statuses/user_timeline.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.user_timeline a_get("/1/statuses/user_timeline.json"). should have_been_made end end end describe "#media_timeline" do context "with a screen name passed" do before do stub_get("/1/statuses/media_timeline.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("media_timeline.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.media_timeline("sferik") a_get("/1/statuses/media_timeline.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return the 20 most recent images posted by the user specified by screen name or user id" do statuses = @client.media_timeline("sferik") statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Google is throwing up a question mark for Sunday's weather in Boston. At least they're being honest. http://t.co/Jh7bAhS" end end context "without a screen name passed" do before do stub_get("/1/statuses/media_timeline.json"). to_return(:body => fixture("media_timeline.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.media_timeline a_get("/1/statuses/media_timeline.json"). should have_been_made end end end describe "#network_timeline" do before do stub_get("/i/statuses/network_timeline.json"). to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.network_timeline a_get("/i/statuses/network_timeline.json"). should have_been_made end it "should return the 20 most recent tweets of the authenticated user that have been retweeted by others" do statuses = @client.network_timeline statuses.should be_an Array statuses.first.should be_a Twitter::Status statuses.first.text.should == "Ruby is the best programming language for hiding the ugly bits." end end end
mislav/twitter
spec/faraday/request_spec.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'helper' describe Faraday::Request do before(:each) do @oauth = Twitter::Request::TwitterOAuth.new(lambda{|env| env}, Hash.new) @request = {:method => "post", :url => "http://test.com/test.json", :request_headers => {}, :body => {:status => "Test"}} end describe "OAuth v1" do it "should encode the entire body when no uploaded media is present" do response = SimpleOAuth::Header.parse(@oauth.call(@request)[:request_headers]["Authorization"]) signature = response.delete(:signature) header = SimpleOAuth::Header.new(:post, "http://test.com/test.json", {:status => "Test"}, response) signature.should == SimpleOAuth::Header.parse(header.to_s)[:signature] end it "should encode none of the body when uploaded media is present" do @request[:body] = {:file => Faraday::UploadIO.new("Rakefile", "Test"), :status => "Test"} response = SimpleOAuth::Header.parse(@oauth.call( @request )[:request_headers]["Authorization"]) signature = response.delete(:signature) header = SimpleOAuth::Header.new(:post, "http://test.com/test.json", {}, response) signature.should == SimpleOAuth::Header.parse(header.to_s)[:signature] end end end
mislav/twitter
spec/twitter/action_spec.rb
require 'helper' describe Twitter::Action do 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 end
mislav/twitter
lib/twitter/entity/user_mention.rb
<gh_stars>1-10 require 'twitter/entity' module Twitter class Entity::UserMention < Twitter::Entity lazy_attr_reader :id, :name, :screen_name end end
mislav/twitter
spec/twitter/client/friends_and_followers_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#follower_ids" do context "with a screen_name passed" do before do stub_get("/1/followers/ids.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follower_ids("sferik") a_get("/1/followers/ids.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). should have_been_made end it "should return an array of numeric IDs for every user following the specified user" do follower_ids = @client.follower_ids("sferik") follower_ids.should be_a Twitter::Cursor follower_ids.ids.should be_an Array follower_ids.ids.first.should == 146197851 end end context "without arguments passed" do before do stub_get("/1/followers/ids.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follower_ids a_get("/1/followers/ids.json"). with(:query => {:cursor => "-1"}). should have_been_made end it "should return an array of numeric IDs for every user following the specified user" do follower_ids = @client.follower_ids follower_ids.should be_a Twitter::Cursor follower_ids.ids.should be_an Array follower_ids.ids.first.should == 146197851 end end end describe "#friend_ids" do context "with a screen_name passed" do before do stub_get("/1/friends/ids.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friend_ids("sferik") a_get("/1/friends/ids.json"). with(:query => {:cursor => "-1", :screen_name => "sferik"}). should have_been_made end it "should return an array of numeric IDs for every user the specified user is following" do friend_ids = @client.friend_ids("sferik") friend_ids.should be_a Twitter::Cursor friend_ids.ids.should be_an Array friend_ids.ids.first.should == 146197851 end end context "without arguments passed" do before do stub_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friend_ids a_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). should have_been_made end it "should return an array of numeric IDs for every user the specified user is following" do friend_ids = @client.friend_ids friend_ids.should be_a Twitter::Cursor friend_ids.ids.should be_an Array friend_ids.ids.first.should == 146197851 end end end describe "#friendship?" do context "with screen names passed" do before do stub_get("/1/friendships/exists.json"). with(:query => {:screen_name_a => "sferik", :screen_name_b => "pengwynn"}). to_return(:body => fixture("true.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/friendships/exists.json"). with(:query => {:screen_name_a => "pengwynn", :screen_name_b => "sferik"}). to_return(:body => fixture("false.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship?("sferik", "pengwynn") a_get("/1/friendships/exists.json"). with(:query => {:screen_name_a => "sferik", :screen_name_b => "pengwynn"}). should have_been_made end it "should return true if user A follows user B" do friendship = @client.friendship?("sferik", "pengwynn") friendship.should be_true end it "should return false if user A does not follow user B" do friendship = @client.friendship?("pengwynn", "sferik") friendship.should be_false end end context "with user IDs passed" do before do stub_get("/1/friendships/exists.json"). with(:query => {:user_id_a => "7505382", :user_id_b => "14100886"}). to_return(:body => fixture("true.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship?(7505382, 14100886) a_get("/1/friendships/exists.json"). with(:query => {:user_id_a => "7505382", :user_id_b => "14100886"}). should have_been_made end end context "with user objects passed" do context "with screen names" do before do stub_get("/1/friendships/exists.json"). with(:query => {:screen_name_a => "sferik", :screen_name_b => "pengwynn"}). to_return(:body => fixture("true.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('screen_name' => 'sferik') user2 = Twitter::User.new('screen_name' => 'pengwynn') @client.friendship?(user1, user2) a_get("/1/friendships/exists.json"). with(:query => {:screen_name_a => "sferik", :screen_name_b => "pengwynn"}). should have_been_made end end context "with user IDs" do before do stub_get("/1/friendships/exists.json"). with(:query => {:user_id_a => "7505382", :user_id_b => "14100886"}). to_return(:body => fixture("true.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('id' => '7505382') user2 = Twitter::User.new('id' => '14100886') @client.friendship?(user1, user2) a_get("/1/friendships/exists.json"). with(:query => {:user_id_a => "7505382", :user_id_b => "14100886"}). should have_been_made end end end end describe "#friendships_incoming" do before do stub_get("/1/friendships/incoming.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships_incoming a_get("/1/friendships/incoming.json"). with(:query => {:cursor => "-1"}). should have_been_made end it "should return an array of numeric IDs for every user who has a pending request to follow the authenticating user" do friendships_incoming = @client.friendships_incoming friendships_incoming.should be_a Twitter::Cursor friendships_incoming.ids.should be_an Array friendships_incoming.ids.first.should == 146197851 end end describe "#friendships_outgoing" do before do stub_get("/1/friendships/outgoing.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships_outgoing a_get("/1/friendships/outgoing.json"). with(:query => {:cursor => "-1"}). should have_been_made end it "should return an array of numeric IDs for every protected user for whom the authenticating user has a pending follow request" do friendships_outgoing = @client.friendships_outgoing friendships_outgoing.should be_a Twitter::Cursor friendships_outgoing.ids.should be_an Array friendships_outgoing.ids.first.should == 146197851 end end describe "#friendship" do context "with screen names passed" do before do stub_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "sferik", :target_screen_name => "pengwynn"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship("sferik", "pengwynn") a_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "sferik", :target_screen_name => "pengwynn"}). should have_been_made end it "should return detailed information about the relationship between two users" do relationship = @client.friendship("sferik", "pengwynn") relationship.should be_a Twitter::Relationship relationship.source.screen_name.should == "sferik" end end context "with numeric screen names passed" do before do stub_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "0", :target_screen_name => "311"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship("0", "311") a_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "0", :target_screen_name => "311"}). should have_been_made end end context "with user IDs passed" do before do stub_get("/1/friendships/show.json"). with(:query => {:source_id => "7505382", :target_id => "14100886"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship(7505382, 14100886) a_get("/1/friendships/show.json"). with(:query => {:source_id => "7505382", :target_id => "14100886"}). should have_been_made end end context "with user objects passed" do context "with screen names" do before do stub_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "sferik", :target_screen_name => "pengwynn"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('screen_name' => 'sferik') user2 = Twitter::User.new('screen_name' => 'pengwynn') @client.friendship(user1, user2) a_get("/1/friendships/show.json"). with(:query => {:source_screen_name => "sferik", :target_screen_name => "pengwynn"}). should have_been_made end end context "with user IDs" do before do stub_get("/1/friendships/show.json"). with(:query => {:source_id => "7505382", :target_id => "14100886"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do user1 = Twitter::User.new('id' => '7505382') user2 = Twitter::User.new('id' => '14100886') @client.friendship(user1, user2) a_get("/1/friendships/show.json"). with(:query => {:source_id => "7505382", :target_id => "14100886"}). should have_been_made end end end end describe "#follow" do context "with :follow => true passed" do before do stub_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382", :follow => "true"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow("sferik", "pengwynn", :follow => true) a_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). should have_been_made a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made a_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382", :follow => "true"}). should have_been_made end it "should return the befriended user" do users = @client.follow("sferik", "pengwynn", :follow => true) users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end context "with :follow => false passed" do before do stub_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow("sferik", "pengwynn", :follow => false) a_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). should have_been_made a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made a_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382"}). should have_been_made end it "should return the befriended user" do users = @client.follow("sferik", "pengwynn", :follow => false) users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end context "without :follow passed" do before do stub_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). to_return(:body => fixture("id_list.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) stub_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow("sferik", "pengwynn") a_get("/1/friends/ids.json"). with(:query => {:cursor => "-1"}). should have_been_made a_get("/1/users/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made a_post("/1/friendships/create.json"). with(:body => {:user_id => "7505382"}). should have_been_made end it "should return the befriended user" do users = @client.follow("sferik", "pengwynn") users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end end describe "#follow!" do context "with :follow => true passed" do before do stub_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik", :follow => "true"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow!("sferik", :follow => true) a_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik", :follow => "true"}). should have_been_made end it "should return the befriended user" do users = @client.follow!("sferik", :follow => true) users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end context "with :follow => false passed" do before do stub_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow!("sferik", :follow => false) a_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the befriended user" do users = @client.follow!("sferik", :follow => false) users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end context "without :follow passed" do before do stub_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.follow!("sferik") a_post("/1/friendships/create.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the befriended user" do users = @client.follow!("sferik") users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end end describe "#unfollow" do before do stub_delete("/1/friendships/destroy.json"). with(:query => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.unfollow("sferik") a_delete("/1/friendships/destroy.json"). with(:query => {:screen_name => "sferik"}). should have_been_made end it "should return the unfollowed" do users = @client.friendship_destroy("sferik") users.should be_an Array users.first.should be_a Twitter::User users.first.name.should == "<NAME>" end end describe "#friendships" do context "with screen names passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("sferik", "pengwynn") a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made end it "should return up to 100 users worth of extended information" do friendships = @client.friendships("sferik", "pengwynn") friendships.should be_an Array friendships.first.should be_a Twitter::User friendships.first.name.should == "<NAME>" friendships.first.connections.should == ["none"] end end context "with numeric screen names passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "0,311"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("0", "311") a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "0,311"}). should have_been_made end end context "with user IDs passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships(7505382, 14100886) a_get("/1/friendships/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). should have_been_made end end context "with both screen names and user IDs passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("sferik", 14100886) a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). should have_been_made end end end describe "#friendships" do context "with screen names passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("sferik", "pengwynn") a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik,pengwynn"}). should have_been_made end it "should return up to 100 users worth of extended information" do friendships = @client.friendships("sferik", "pengwynn") friendships.should be_an Array friendships.first.should be_a Twitter::User friendships.first.name.should == "<NAME>" friendships.first.connections.should == ["none"] end end context "with numeric screen names passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "0,311"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("0", "311") a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "0,311"}). should have_been_made end end context "with user IDs passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships(7505382, 14100886) a_get("/1/friendships/lookup.json"). with(:query => {:user_id => "7505382,14100886"}). should have_been_made end end context "with both screen names and user IDs passed" do before do stub_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). to_return(:body => fixture("friendships.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendships("sferik", 14100886) a_get("/1/friendships/lookup.json"). with(:query => {:screen_name => "sferik", :user_id => "14100886"}). should have_been_made end end end describe "#friendship_update" do before do stub_post("/1/friendships/update.json"). with(:body => {:screen_name => "sferik", :retweets => "true"}). to_return(:body => fixture("relationship.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.friendship_update("sferik", :retweets => true) a_post("/1/friendships/update.json"). with(:body => {:screen_name => "sferik", :retweets => "true"}). should have_been_made end it "should return detailed information about the relationship between two users" do relationship = @client.friendship_update("sferik", :retweets => true) relationship.should be_a Twitter::Relationship relationship.source.screen_name.should == "sferik" end end describe "#no_retweet_ids" do before do stub_get("/1/friendships/no_retweet_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.no_retweet_ids a_get("/1/friendships/no_retweet_ids.json"). should have_been_made end it "should return detailed information about the relationship between two users" do no_retweet_ids = @client.no_retweet_ids no_retweet_ids.should be_an Array no_retweet_ids.first.should be_an Integer no_retweet_ids.first.should == 47 end end describe "#accept" do before do stub_post("/1/friendships/accept.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.accept("sferik") a_post("/1/friendships/accept.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the accepted user" do user = @client.accept("sferik") user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#deny" do before do stub_post("/1/friendships/deny.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.deny("sferik") a_post("/1/friendships/deny.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the denied user" do user = @client.deny("sferik") user.should be_a Twitter::User user.name.should == "<NAME>" end end end
mislav/twitter
lib/twitter/error/client_error.rb
require 'twitter/error' module Twitter # Raised when Twitter returns a 4xx HTTP status code class Error::ClientError < Twitter::Error end end
mislav/twitter
spec/twitter/oembed_spec.rb
<filename>spec/twitter/oembed_spec.rb require 'helper' describe Twitter::OEmbed do describe "#author_url" do it "should return the author's url" do oembed = Twitter::OEmbed.new('author_url' => 'https://twitter.com/sferik') oembed.author_url.should == "https://twitter.com/sferik" end it "should return nil when not set" do author_url = Twitter::OEmbed.new.author_url author_url.should be_nil end end describe "#author_name" do it "should return the author's name" do oembed = Twitter::OEmbed.new('author_name' => '<NAME>') oembed.author_name.should == "<NAME>" end it "should return nil when not set" do author_name = Twitter::OEmbed.new.author_name author_name.should be_nil end end describe "#cache_age" do it "should return the cache_age" do oembed = Twitter::OEmbed.new('cache_age' => '31536000000') oembed.cache_age.should == "31536000000" end it "should return nil when not set" do cache_age = Twitter::OEmbed.new.cache_age cache_age.should be_nil end end describe "#height" do it "should return the height" do oembed = Twitter::OEmbed.new('height' => 200) oembed.height.should == 200 end it "should return it as a Fixnum" do oembed = Twitter::OEmbed.new('height' => 200) oembed.height.should be_a Fixnum end it "should return nil when not set" do height = Twitter::OEmbed.new.height height.should be_nil end end describe "#html" do it "should return the html" do oembed = Twitter::OEmbed.new('html' => '<blockquote>all my <b>witty tweet</b> stuff here</blockquote>') oembed.html.should == "<blockquote>all my <b>witty tweet</b> stuff here</blockquote>" end it "should return nil when not set" do html = Twitter::OEmbed.new.html html.should be_nil end end describe "#provider_name" do it "should return the provider_name" do oembed = Twitter::OEmbed.new('provider_name' => 'Twitter') oembed.provider_name.should == "Twitter" end it "should return nil when not set" do provider_name = Twitter::OEmbed.new.provider_name provider_name.should be_nil end end describe "#provider_url" do it "should return the provider_url" do oembed = Twitter::OEmbed.new('provider_url' => 'http://twitter.com') oembed.provider_url.should == "http://twitter.com" end it "should return nil when not set" do provider_url = Twitter::OEmbed.new.provider_url provider_url.should be_nil end end describe "#type" do it "should return the type" do oembed = Twitter::OEmbed.new('type' => 'rich') oembed.type.should == "rich" end it "should return nil when not set" do type = Twitter::OEmbed.new.type type.should be_nil end end describe "#width" do it "should return the width" do oembed = Twitter::OEmbed.new('width' => 550) oembed.width.should == 550 end it "should return it as a Fixnum" do oembed = Twitter::OEmbed.new('width' => 550) oembed.width.should be_a Fixnum end it "should return nil when not set" do width = Twitter::OEmbed.new.width width.should be_nil end end describe "#url" do it "should return the url" do oembed = Twitter::OEmbed.new('url' => 'https://twitter.com/twitterapi/status/133640144317198338') oembed.url.should == "https://twitter.com/twitterapi/status/133640144317198338" end it "should return nil when not set" do url = Twitter::OEmbed.new.url url.should be_nil end end describe "#version" do it "should return the version" do oembed = Twitter::OEmbed.new('version' => '1.0') oembed.version.should == "1.0" end it "should return nil when not set" do version = Twitter::OEmbed.new.version version.should be_nil end end end
mislav/twitter
lib/twitter/follow.rb
<filename>lib/twitter/follow.rb require 'twitter/action' require 'twitter/user' module Twitter class Follow < Twitter::Action lazy_attr_reader :target_objects # A collection of users who followed a user # # @return [Array<Twitter::User>] def sources @sources = Array(@attrs['sources']).map do |user| Twitter::User.new(user) end end # A collection containing the followed user # # @return [Array<Twitter::User>] def targets @targets = Array(@attrs['targets']).map do |user| Twitter::User.new(user) end end end end
mislav/twitter
spec/twitter/geo_factory_spec.rb
require 'helper' describe Twitter::GeoFactory do describe ".new" do it "should generate a Point" do geo = Twitter::GeoFactory.new('type' => 'Point') geo.should be_a Twitter::Point end it "should generate a Polygon" do geo = Twitter::GeoFactory.new('type' => 'Polygon') geo.should be_a Twitter::Polygon end it "should raise an ArgumentError when type is not specified" do lambda do Twitter::GeoFactory.new({}) end.should raise_error(ArgumentError, "argument must have a 'type' key") end end end
mislav/twitter
lib/twitter/error/enhance_your_calm.rb
require 'twitter/error/client_error' module Twitter # Raised when Twitter returns the HTTP status code 420 class Error::EnhanceYourCalm < Twitter::Error::ClientError # The number of seconds your application should wait before requesting date from the Search API again # # @see http://dev.twitter.com/pages/rate-limiting def retry_after @http_headers.values_at('retry-after', 'Retry-After').detect{|value| value }.to_i end end end
mislav/twitter
lib/twitter/entity/url.rb
<gh_stars>1-10 require 'twitter/entity' module Twitter class Entity::Url < Twitter::Entity lazy_attr_reader :display_url, :expanded_url, :url end end
mislav/twitter
lib/twitter/cursor.rb
require 'twitter/core_ext/kernel' module Twitter class Cursor attr_reader :collection attr_accessor :attrs alias :to_hash :attrs # Initializes a new Cursor object # # @param attrs [Hash] # @params method [String, Symbol] The name of the method to return the collection # @params klass [Class] The class to instantiate object in the collection # @return [Twitter::Cursor] def initialize(attrs, method, klass=nil) @attrs = attrs @collection = Array(attrs[method.to_s]).map do |item| if klass klass.new(item) else item end end class_eval do alias_method method.to_sym, :collection end end def next_cursor @attrs['next_cursor'] end alias :next :next_cursor def previous_cursor @attrs['previous_cursor'] end alias :previous :previous_cursor # @return [Boolean] def first? previous_cursor.zero? end alias :first :first? # @return [Boolean] def last? next_cursor.zero? end alias :last :last? end end
mislav/twitter
spec/twitter/client/help_spec.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#configuration" do before do stub_get("/1/help/configuration.json"). to_return(:body => fixture("configuration.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.configuration a_get("/1/help/configuration.json"). should have_been_made end it "should return Twitter's current configuration" do configuration = @client.configuration configuration.should be_a Twitter::Configuration configuration.characters_reserved_per_media.should == 20 end end describe "#languages" do before do stub_get("/1/help/languages.json"). to_return(:body => fixture("languages.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.languages a_get("/1/help/languages.json"). should have_been_made end it "should return the list of languages supported by Twitter" do languages = @client.languages languages.should be_an Array languages.first.should be_a Twitter::Language languages.first.name.should == "Portuguese" end end end
mislav/twitter
lib/twitter/place.rb
<gh_stars>1-10 require 'twitter/geo_factory' require 'twitter/identifiable' module Twitter class Place < Twitter::Identifiable lazy_attr_reader :attributes, :country, :full_name, :name, :url, :woeid alias :woe_id :woeid # @param other [Twitter::Place] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end # @return [Twitter::Point, Twitter::Polygon] def bounding_box @bounding_box ||= Twitter::GeoFactory.new(@attrs['bounding_box']) unless @attrs['bounding_box'].nil? end # @return [String] def country_code @country_code ||= @attrs['country_code'] || @attrs['countryCode'] end # @return [Integer] def parent_id @parent_id ||= @attrs['parentid'] end # @return [String] def place_type @place_type ||= @attrs['place_type'] || @attrs['placeType'] && @attrs['placeType']['name'] end end end
mislav/twitter
lib/twitter/relationship.rb
require 'twitter/base' require 'twitter/user' module Twitter class Relationship < Twitter::Base # @return [Twitter::User] def source @source ||= Twitter::User.new(@attrs['source']) unless @attrs['source'].nil? end # @return [Twitter::User] def target @target ||= Twitter::User.new(@attrs['target']) unless @attrs['target'].nil? end end end
mislav/twitter
lib/twitter/size.rb
require 'twitter/base' module Twitter class Size < Twitter::Base lazy_attr_reader :h, :resize, :w alias :height :h alias :width :w # @param other [Twitter::Size] # @return [Boolean] def ==(other) super || (other.class == self.class && other.h == self.h && other.w == self.w) end end end
mislav/twitter
lib/twitter/polygon.rb
require 'twitter/base' module Twitter class Polygon < Twitter::Base lazy_attr_reader :coordinates # @param other [Twitter::Polygon] # @return [Boolean] def ==(other) super || (other.class == self.class && other.coordinates == self.coordinates) end end end
mislav/twitter
lib/twitter/status.rb
<reponame>mislav/twitter require 'twitter/client' require 'twitter/core_ext/hash' require 'twitter/creatable' require 'twitter/entity/hashtag' require 'twitter/entity/url' require 'twitter/entity/user_mention' require 'twitter/geo_factory' require 'twitter/identifiable' require 'twitter/media_factory' require 'twitter/metadata' require 'twitter/oembed' require 'twitter/place' require 'twitter/user' module Twitter class Status < Twitter::Identifiable include Twitter::Creatable lazy_attr_reader :favorited, :favoriters, :from_user, :from_user_id, :from_user_name, :in_reply_to_screen_name, :in_reply_to_attrs_id, :in_reply_to_status_id, :in_reply_to_user_id, :iso_language_code, :profile_image_url, :profile_image_url_https, :repliers, :retweeted, :retweeters, :source, :text, :to_user, :to_user_id, :to_user_name, :truncated alias :favorited? :favorited alias :retweeted? :retweeted alias :truncated? :truncated # @param other [Twitter::Status] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end # @note If favoriters_count is > 50 it will return the string 50+. # @return [String] def favoriters_count @attrs['favoriters_count'] end alias :favorite_count :favoriters_count # @return [String] def from_user @attrs['from_user'] || self.user && self.user.screen_name end # @return [String] # @note May be > 140 characters. def full_text self.retweeted_status && self.retweeted_status.user ? "RT @#{self.retweeted_status.user.screen_name}: #{self.retweeted_status.text}" : self.text end # @return [Twitter::Point, Twitter::Polygon] def geo @geo ||= Twitter::GeoFactory.new(@attrs['geo']) unless @attrs['geo'].nil? end # @note Must include entities in your request for this method to work # @return [Array<Twitter::Entity::Hashtag>] def hashtags @hashtags ||= unless @attrs['entities'].nil? Array(@attrs['entities']['hashtags']).map do |hashtag| Twitter::Entity::Hashtag.new(hashtag) end else warn "#{Kernel.caller.first}: To get hashtags, you must pass `:include_entities => true` when requesting the Twitter::Status." end end # @note Must include entities in your request for this method to work # @return [Array] def media @media ||= unless @attrs['entities'].nil? Array(@attrs['entities']['media']).map do |media| Twitter::MediaFactory.new(media) end else warn "#{Kernel.caller.first}: To get media, you must pass `:include_entities => true` when requesting the Twitter::Status." end end # @return [Twitter::Metadata] def metadata @metadata ||= Twitter::Metadata.new(@attrs['metadata']) unless @attrs['metadata'].nil? end # @return [Twitter::OEmbed] def oembed(options={}) @client ||= Twitter::Client.new @client.oembed(@attrs['id'], options) unless @attrs['id'].nil? end # @return [Twitter::Place] def place @place ||= Twitter::Place.new(@attrs['place']) unless @attrs['place'].nil? end # @note If repliers_count is > 50 it will return the string 50+. # @return [String] def repliers_count @attrs['repliers_count'] end alias :reply_count :repliers_count # @note If retweeters_count is > 50 it will return the string 50+. # @return [String] def retweeters_count @attrs['retweet_count'] || @attrs['retweeters_count'] end alias :retweet_count :retweeters_count # If this status is itself a retweet, the original tweet is available here. # # @return [Twitter::Status] def retweeted_status @retweeted_status ||= self.class.new(@attrs['retweeted_status']) unless @attrs['retweeted_status'].nil? end # @note Must include entities in your request for this method to work # @return [Array<Twitter::Entity::Url>] def urls @urls ||= unless @attrs['entities'].nil? Array(@attrs['entities']['urls']).map do |url| Twitter::Entity::Url.new(url) end else warn "#{Kernel.caller.first}: To get URLs, you must pass `:include_entities => true` when requesting the Twitter::Status." end end # @return [Twitter::User] def user @user ||= Twitter::User.new(@attrs.dup['user'].merge('status' => @attrs.except('user'))) unless @attrs['user'].nil? end # @note Must include entities in your request for this method to work # @return [Array<Twitter::Entity::UserMention>] def user_mentions @user_mentions ||= unless @attrs['entities'].nil? Array(@attrs['entities']['user_mentions']).map do |user_mention| Twitter::Entity::UserMention.new(user_mention) end else warn "#{Kernel.caller.first}: To get user mentions, you must pass `:include_entities => true` when requesting the Twitter::Status." end end end end
mislav/twitter
spec/twitter/polygon_spec.rb
describe Twitter::Polygon do before do @polygon = Twitter::Polygon.new('coordinates' => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]) end describe "#==" do it "should return true when coordinates are equal" do other = Twitter::Polygon.new('coordinates' => [[[-122.40348192, 37.77752898], [-122.387436, 37.77752898], [-122.387436, 37.79448597], [-122.40348192, 37.79448597]]]) (@polygon == other).should be_true end it "should return false when coordinates are not equal" do other = Twitter::Polygon.new('coordinates' => [[[37.77752898, -122.40348192], [37.77752898, -122.387436], [37.79448597, -122.387436], [37.79448597, -122.40348192]]]) (@polygon == other).should be_false end end end
mislav/twitter
lib/twitter/error/bad_gateway.rb
require 'twitter/error/server_error' module Twitter # Raised when Twitter returns the HTTP status code 502 class Error::BadGateway < Twitter::Error::ServerError end end
mislav/twitter
lib/twitter/geo_factory.rb
require 'twitter/point' require 'twitter/polygon' module Twitter class GeoFactory # Instantiates a new geo object # # @param attrs [Hash] # @raise [ArgumentError] Error raised when supplied argument is missing a 'type' key. # @return [Twitter::Point, Twitter::Polygon] def self.new(geo={}) type = geo.delete('type') if type Twitter.const_get(type.capitalize.to_sym).new(geo) else raise ArgumentError, "argument must have a 'type' key" end end end end
mislav/twitter
lib/twitter/user.rb
require 'twitter/authenticatable' require 'twitter/core_ext/hash' require 'twitter/creatable' require 'twitter/identifiable' require 'twitter/status' module Twitter class User < Twitter::Identifiable include Twitter::Authenticatable include Twitter::Creatable lazy_attr_reader :all_replies, :blocking, :can_dm, :connections, :contributors_enabled, :default_profile, :default_profile_image, :description, :favourites_count, :follow_request_sent, :followed_by, :followers_count, :following, :friends_count, :geo_enabled, :is_translator, :lang, :listed_count, :location, :marked_spam, :name, :notifications, :notifications_enabled, :profile_background_color, :profile_background_image_url, :profile_background_image_url_https, :profile_background_tile, :profile_image_url, :profile_image_url_https, :profile_link_color, :profile_sidebar_border_color, :profile_sidebar_fill_color, :profile_text_color, :profile_use_background_image, :protected, :screen_name, :statuses_count, :time_zone, :url, :utc_offset, :verified, :want_retweets alias :all_replies? :all_replies alias :blocking? :blocking alias :can_dm? :can_dm alias :contributors_enabled? :contributors_enabled alias :default_profile? :default_profile alias :default_profile_image? :default_profile_image alias :follow_request_sent? :follow_request_sent alias :following? :following alias :followed_by? :followed_by alias :favorites :favourites_count alias :favorites_count :favourites_count alias :favourites :favourites_count alias :followers :followers_count alias :friends :friends_count alias :geo_enabled? :geo_enabled alias :is_translator? :is_translator alias :listed :listed_count alias :marked_spam? :marked_spam alias :notifications? :notifications alias :notifications_enabled? :notifications_enabled alias :profile_background_tile? :profile_background_tile alias :profile_use_background_image? :profile_use_background_image alias :protected? :protected alias :statuses :statuses_count alias :translator :is_translator alias :translator? :is_translator alias :updates :statuses_count alias :verified? :verified alias :want_retweets? :want_retweets # @param other [Twitter::User] # @return [Boolean] def ==(other) super || (other.class == self.class && other.id == self.id) end # @return [Twitter::Status] def status @status ||= Twitter::Status.new(@attrs.dup['status'].merge('user' => @attrs.except('status'))) unless @attrs['status'].nil? end end end
mislav/twitter
spec/twitter/client/notification_spec.rb
require 'helper' describe Twitter::Client do before do @client = Twitter::Client.new end describe "#enable_notifications" do before do stub_post("/1/notifications/follow.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.enable_notifications("sferik") a_post("/1/notifications/follow.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the specified user when successful" do user = @client.enable_notifications("sferik") user.should be_a Twitter::User user.name.should == "<NAME>" end end describe "#disable_notifications" do before do stub_post("/1/notifications/leave.json"). with(:body => {:screen_name => "sferik"}). to_return(:body => fixture("sferik.json"), :headers => {:content_type => "application/json; charset=utf-8"}) end it "should request the correct resource" do @client.disable_notifications("sferik") a_post("/1/notifications/leave.json"). with(:body => {:screen_name => "sferik"}). should have_been_made end it "should return the specified user when successful" do user = @client.disable_notifications("sferik") user.should be_a Twitter::User user.name.should == "<NAME>" end end end
mislav/twitter
spec/twitter/size_spec.rb
<reponame>mislav/twitter<gh_stars>1-10 require 'helper' describe Twitter::Size do describe "#==" do it "should return true when height and width are equal" do size = Twitter::Size.new('h' => 1, 'w' => 1) other = Twitter::Size.new('h' => 1, 'w' => 1) (size == other).should be_true end it "should return false when height and width are not equal" do size = Twitter::Size.new('h' => 1, 'w' => 1) other = Twitter::Size.new('h' => 1, 'w' => 2) (size == other).should be_false end end end
mislav/twitter
spec/twitter/photo_spec.rb
require 'helper' describe Twitter::Photo do describe "#==" do it "should return true when ids and classes are equal" do photo = Twitter::Photo.new('id' => 1) other = Twitter::Photo.new('id' => 1) (photo == other).should be_true end it "should return false when classes are not equal" do photo = Twitter::Photo.new('id' => 1) other = Twitter::User.new('id' => 1) (photo == other).should be_false end it "should return false when ids are not equal" do photo = Twitter::Photo.new('id' => 1) other = Twitter::Photo.new('id' => 2) (photo == other).should be_false end end describe "#sizes" do it "should return a hash of Sizes when sizes is set" do sizes = Twitter::Photo.new('sizes' => {'small' => {'h' => 226, 'w' => 340, 'resize' => 'fit'}, 'large' => {'h' => 466, 'w' => 700, 'resize' => 'fit'}, 'medium' => {'h' => 399, 'w' => 600, 'resize' => 'fit'}, 'thumb' => {'h' => 150, 'w' => 150, 'resize' => 'crop'}}).sizes sizes.should be_a Hash sizes['small'].should be_a Twitter::Size end it "should be empty when sizes is not set" do sizes = Twitter::Photo.new.sizes sizes.should be_empty end end end