repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
kronus/angular-ruby-2014-example
config/routes.rb
<reponame>kronus/angular-ruby-2014-example CafeTownsendAngularRails::Application.routes.draw do get 'login', to: 'sessions#create', as: :login resources :sessions resources :employees root to: 'sessions#create' end
kronus/angular-ruby-2014-example
app/views/employees/index.json.jbuilder
json.array!(@employees) do |employee| json.cache! employee do json.extract! employee, :id, :first_name, :last_name, :email, :start_date end end
kronus/angular-ruby-2014-example
app/models/user.rb
<reponame>kronus/angular-ruby-2014-example class User < ActiveRecord::Base has_secure_password validates_presence_of :password, on: :create end
kronus/angular-ruby-2014-example
spec/factories/users.rb
<filename>spec/factories/users.rb require 'faker' FactoryGirl.define do fake_password = <PASSWORD>(5) factory :user do name { Faker::Name.first_name } password <PASSWORD> password_confirmation <PASSWORD> end end
kronus/angular-ruby-2014-example
spec/factories/employees.rb
<gh_stars>10-100 require 'faker' FactoryGirl.define do factory :employee do first_name { Faker::Name.first_name } last_name { Faker::Name.last_name } email { Faker::Internet.email } start_date { Date.today-rand(10_000) } end end
kronus/angular-ruby-2014-example
spec/support/controller_macros.rb
module ControllerMacros def login_user(user) session[:user_id] = user.id end end
kronus/angular-ruby-2014-example
spec/models/user_spec.rb
<reponame>kronus/angular-ruby-2014-example<filename>spec/models/user_spec.rb require'spec_helper' describe 'User' do context "valid params" do it 'build an user' do expect(build(:user)).to be_valid end end context "invalid params" do it "without a password" do expect(build(:user, password: '')).to have(2).errors_on(:password) end it "without a password confirmation" do expect(build(:user, password_confirmation: '')).to have(2).errors_on(:password_confirmation) end end end
kronus/angular-ruby-2014-example
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. CafeTownsendAngularRails::Application.config.session_store :cookie_store, key: '_CafeTownsend-Angular-Rails_session'
kronus/angular-ruby-2014-example
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :render_single_page private def ensure_authenticated if session[:user_id].blank? render :json => { authorized: false } end end def render_single_page render 'layouts/application' if request.format == Mime::HTML end end
kronus/angular-ruby-2014-example
spec/controllers/sessions_controller_spec.rb
<reponame>kronus/angular-ruby-2014-example require 'spec_helper' describe SessionsController do let!(:user_created) { create(:user) } # saved in db before :each do # avoid rendering html of single page app (RSpec only) request.env["HTTP_ACCEPT"] = "application/json" end # create # --------------------------------------------- describe "POST create" do context "with valid params" do it "an user is created and returned" do post :create, {name: user_created.name, password: <PASSWORD>} expected_json = {user: user_created, authorized: 'true' }.to_json expect(response.body).to eq expected_json end end context "with invalid params" do it "an user is not logged in with an invalid password" do post :create, {name: user_created.name, password: <PASSWORD>!} expected_json = {authorized: 'false' }.to_json expect(response.body).to eq expected_json end it "an user is not logged with an invalid name" do post :create, {name: user_created.name.reverse!, password: <PASSWORD>} expected_json = {authorized: 'false' }.to_json expect(response.body).to eq expected_json end end # delete # --------------------------------------------- describe "DELETE destroy" do before :each do login_user user_created end it "returns false status of authorized" do delete :destroy, {id: user_created.to_param} expected_json = {authorized: 'false' }.to_json expect(response.body).to eq expected_json end it "destroys the session" do delete :destroy, {id: user_created.to_param} expect(session[:user_id]).to be_nil end end end end
kronus/angular-ruby-2014-example
spec/models/employee_spec.rb
<filename>spec/models/employee_spec.rb require'spec_helper' describe 'Employee' do it 'should be valid' do expect(build(:employee)).to be_valid end it "should invalid without a first name" do expect(build(:employee, first_name: '')).to_not be_valid end it "should invalid without a last name" do expect(build(:employee, last_name: '')).to_not be_valid end it "should invalid without an email" do expect(build(:employee, email: '')).to_not be_valid end it "should invalid without a start date" do expect(build(:employee, start_date: nil)).to_not be_valid end it "should store into db", :focus do expect(create(:employee)).to_not be_nil end end
kronus/angular-ruby-2014-example
app/controllers/sessions_controller.rb
<reponame>kronus/angular-ruby-2014-example class SessionsController < ApplicationController respond_to :json # POST /sessions def create user = User.find_by(name: params[:name]) if user && user.authenticate(params[:password]) session[:user_id] = user.id render json: { user: user, authorized: 'true' } else #raise StandardError render json: { authorized: 'false' } end end # DELETE /sessions/1 def destroy session[:user_id] = nil render json: { authorized: 'false' } end end
kronus/angular-ruby-2014-example
config/initializers/formtastic.rb
<reponame>kronus/angular-ruby-2014-example module Formtastic module DatePicker protected def datepicker_input(method, options = {}) format = options[:format] || ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default] || '%d %b %Y' string_input(method, datepicker_options(format, object.send(method)).merge(options)) end # Generate html input options for the datepicker_input # def datepicker_options(format, value = nil) datepicker_options = {:value => value.try(:strftime, format), :input_html => {:class => 'ui-datepicker'}} end end end Formtastic::SemanticFormBuilder.send(:include, Formtastic::DatePicker)
kronus/angular-ruby-2014-example
app/controllers/employees_controller.rb
<filename>app/controllers/employees_controller.rb<gh_stars>0 class EmployeesController < ApplicationController before_filter :ensure_authenticated before_filter :set_employee, :except => [:index, :create] respond_to :json # GET /employees # GET /employees.json def index @employees = Employee.all end # GET /employees/new def new end # GET /employees/1 # GET /employees/1.json def show render json: @employee end # GET /employees/1/edit def edit end # POST /employees def create @employee = Employee.new(employee_params) if @employee.save render json: @employee else render json: @employee.errors, status: :unprocessable_entity end end # PATCH/PUT /contacts/1.json def update @employee.update_attributes!(employee_params) render json: @employee end # DELETE /employees/1 def destroy @employee.destroy head :no_content end private def set_employee @employee = Employee.find(params[:id]) end def employee_params params.require(:employee).permit(:first_name, :last_name, :email, :start_date) end end
noisegaze/cli_project
lib/list.rb
require 'net/http' require 'open-uri' require 'json' #require 'open-ssl' require 'pry' class List attr_accessor :city, :state @@all = [] def initialize(city,state) @city = city @state = state #save end def location(location_endpoint_url) location_query = @city + "," + @state uri = URI.parse(location_endpoint_url) request = Net::HTTP::Post.new(uri) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = '<KEY>' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "language=en_US&q=" + location_query return request.body binding.pry end def search(search_endpoint_url) restaurant_search = self.location uri = URI.parse(search_endpoint_url) request = Net::HTTP::Post.new(uri) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = '<KEY>' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "limit=30&language=en_US&location_id=" + restaurant_search end def details(details_endpoint_url) restaurant_details = self.search uri = URI.parse(details_endpoint_url) request = Net::HTTP::Post.new(url) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = 'cbf3a9a4a2msh016640a1b0b9654p167a44jsn6a865e1db18a' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "currency=USD&language=en_US&location_id=" + restaurant_details end def save @@all << self end def self.all @@all end def restart @@all.clear end end
noisegaze/cli_project
lib/reference.rb
require 'uri' require 'net/http' require 'openssl' url = URI("https://worldwide-restaurants.p.rapidapi.com/search") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = '<KEY>' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "limit=30&language=en_US&location_id=297704&currency=USD" response = http.request(request) puts response.read_body require 'uri' require 'net/http' require 'openssl' url = URI("https://worldwide-restaurants.p.rapidapi.com/typeahead") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = '<KEY>' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "language=en_US&q=band" response = http.request(request) puts response.read_body require 'uri' require 'net/http' require 'openssl' url = URI("https://worldwide-restaurants.p.rapidapi.com/detail") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(url) request["x-rapidapi-host"] = 'worldwide-restaurants.p.rapidapi.com' request["x-rapidapi-key"] = '<KEY>' request["content-type"] = 'application/x-www-form-urlencoded' request.body = "currency=USD&language=en_US&location_id=15333482" response = http.request(request) puts response.read_body
lryndavis/ruby_recipes
lib/recipe.rb
class Recipe < ActiveRecord::Base has_and_belongs_to_many(:tags) has_and_belongs_to_many(:ingredients) validates(:recipe_name, :presence => true) before_save(:titleize_recipe_name) private define_method(:titleize_recipe_name) do self.recipe_name=(recipe_name().titleize()) end end
lryndavis/ruby_recipes
spec/ingredient_spec.rb
<reponame>lryndavis/ruby_recipes require('spec_helper') describe(Ingredient) do it("converts the ingredient entry to titlecase") do ingredient = Ingredient.create({:ingredient_name => "pepper"}) expect(ingredient.ingredient_name()).to(eq("Pepper")) end end
lryndavis/ruby_recipes
spec/tag_spec.rb
require('spec_helper') describe(Tag) do it("converts the tag to titlecase") do tag = Tag.create({:category => "vegan"}) expect(tag.category()).to(eq("Vegan")) end it("validates presence of a tag entry") do tag = Tag.new({:category => ""}) expect(tag.save()).to(eq(false)) end end
lryndavis/ruby_recipes
lib/tag.rb
<filename>lib/tag.rb class Tag < ActiveRecord::Base has_and_belongs_to_many(:recipes) validates(:category, :presence => true) before_save(:titleize_category) private define_method(:titleize_category) do self.category=(category().titleize()) end end
lryndavis/ruby_recipes
spec/recipe_integration_spec.rb
<reponame>lryndavis/ruby_recipes<filename>spec/recipe_integration_spec.rb require('spec_helper') describe('ability to add a new recipe to the application', {:type => :feature}) do it('allows a user to add a new recipe to the list of recipes') do visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Potato Soup') end end describe('ability to add tags to the application', {:type => :feature}) do it('allows a user to add a new tag') do visit('/') fill_in('category', :with => "Breakfast") click_button('Add Tag') expect(page).to have_content('Breakfast') end end describe('ability to add instructions to each recipe', {:type => :feature}) do it('allows th user to add insutructions') do visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Tomato Soup') click_link('Tomato Soup', :match => :first) expect(page).to have_content('Add Instructions Below:') fill_in('instructions', :with => "Make the Soup") click_button("Submit", :match => :first) expect(page).to have_content('Make the Soup') end end describe('ability to add tags to each recipe', {:type => :feature}) do it('allows the user to add tags to each recipe') do visit('/') fill_in('category', :with => "Vegan") click_button('Add Tag') expect(page).to have_content('Vegan') visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Tomato Soup') click_link('Tomato Soup', :match => :first) expect(page).to have_content('Add Tags:') select "Vegan", :from => "tag_id" click_button('Add Tag') expect(page).to have_content('Vegan') end end describe('ability to add ingredients to each recipe', {:type => :feature}) do it('allows the user to add ingredients to each recipe') do visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Tomato Soup') click_link('Tomato Soup', :match => :first) expect(page).to have_content('Add an Ingredient:') fill_in('ingredient_name', :with => "Pepper") click_button('Add') expect(page).to have_content('Pepper') end end describe('ability to delete recipes', {:type => :feature}) do it('allows the user to delete individual recipes') do visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Tomato Soup') click_link('Tomato Soup') click_button('Delete this Recipe') expect(page).not_to(have_content('Tomato Soup')) end end describe('ability to update tags', {:type => :feature}) do it('allows the user to update tag names') do visit('/') fill_in('category', :with => "Vegan") click_button('Add Tag') expect(page).to have_content('Vegan') click_link('Vegan') fill_in('category', :with => "Vegan Friendly") click_button('Update Tag') expect(page).to have_content('Vegan Friendly') end end describe('ability to delete tags', {:type => :feature}) do it('allows the user to delete individual tags') do visit('/') fill_in('category', :with => "Vegan") click_button('Add Tag') expect(page).to have_content('Vegan') click_link('Vegan') click_button('Delete this Tag') expect(page).not_to(have_content('Vegan')) end end describe('ability to search recipes by tag', {:type => :feature}) do it('allows the user to search for recipes based on their corresponding tags') do visit('/') fill_in('category', :with => "Vegan") click_button('Add Tag') expect(page).to have_content('Vegan') visit('/') fill_in('recipe_name', :with => "<NAME>") click_button('Add Recipe') expect(page).to have_content('Tomato Soup') click_link('Tomato Soup', :match => :first) expect(page).to have_content('Add Tags:') select "Vegan", :from => "tag_id" click_button('Add Tag') expect(page).to have_content('Vegan') click_link('HOME') expect(page).to have_content('Search by Tags:') click_link('Vegan') expect(page).to have_content('Tomato Soup') end end
lryndavis/ruby_recipes
spec/recipe_spec.rb
require('spec_helper') describe(Recipe) do it("converts the recipe name to titlecase") do recipe = Recipe.create({:recipe_name => "potato soup"}) expect(recipe.recipe_name()).to(eq("Potato Soup")) end it("validates presence of a recipe name entry") do recipe = Recipe.new({:recipe_name => ""}) expect(recipe.save()).to(eq(false)) end end
lryndavis/ruby_recipes
lib/ingredient.rb
<filename>lib/ingredient.rb class Ingredient < ActiveRecord::Base has_and_belongs_to_many(:recipes) before_save(:titleize_ingredient_name) private define_method(:titleize_ingredient_name) do self.ingredient_name=(ingredient_name().titleize()) end end
ankane/toucan
toucan.rb
require "redis" class Toucan def initialize @redis = Redis.new @prefix = "toucan" end def add_event(timestamp, category, key, value, properties = {}, properties_with_counts = {}) timestamp = timestamp.to_i pairs = {} begin pairs[key.join(".")] = value end while key.pop and !key.empty? # batch commands # TODO: make redis commands non-blocking @redis.multi do pairs.each do |key, val| @redis.incrby("#{@prefix}.#{category}.lifetime.#{key}", val) hour = round_time(timestamp, 3600) @redis.incrby("#{@prefix}.#{category}.hour.#{hour}.#{key}", val) minute = round_time(timestamp, 60) @redis.incrby("#{@prefix}.#{category}.minute.#{minute}.#{key}", val) # use date for day YYYY-MM-DD instead of timestamp # need to account for time zone day = Time.at(timestamp).to_date.strftime("%Y-%m-%d") @redis.incrby("#{@prefix}.#{category}.day.#{day}.#{key}", val) end end end def minute_counts(category, key, points = 10, seconds = 60, prefix = "minute") last = round_time(Time.now, seconds) first = last - (points - 1) * seconds steps = *(first..last).step(seconds) count_helper(category, key, prefix, steps) end def hour_counts(category, key, points = 10) minute_counts(category, key, points, 3600, "hour") end def day_counts(category, key, points = 10) last = Date.today first = last - (points - 1) steps = *first.step(last) count_helper(category, key, "day", steps) end def lifetime_counts(category, key) @redis.get("#{@prefix}.#{category}.lifetime.#{key.join(".")}").to_i end protected def count_helper(category, key, prefix, steps) key = key.join(".") keys = steps.map{|step| "#{@prefix}.#{category}.#{prefix}.#{step}.#{key}"} # get keys and replace nils with zero values = @redis.mget(*keys).map{|val| (val || 0).to_i } Hash[steps.map{|step| step = step.strftime("%Y-%m-%d") if step.is_a?(Date); [step, values.shift]}] end # http://stackoverflow.com/questions/449271/how-to-round-a-time-down-to-the-nearest-15-minutes-in-ruby/449322#449322 def round_time(timestamp, seconds = 60) (timestamp.to_f / seconds).floor * seconds end end
ankane/toucan
examples.rb
require "rubygems" require "bundler/setup" require "pp" require_relative "toucan" toucan = Toucan.new toucan.add_event(Time.now, "url", ["com", "amazon", "music"], 1) toucan.add_event(Time.now, "url", ["com", "facebook", "www"], 1) puts "minute - com" pp toucan.minute_counts("url", ["com"]) puts puts "hour - amazon.com" pp toucan.hour_counts("url", ["com", "amazon"]) puts puts "day - com - 5 points" pp toucan.day_counts("url", ["com"], 5) puts puts "lifetime - www.facebook.com" pp toucan.lifetime_counts("url", ["com", "facebook", "www"]) puts
ankane/toucan
benchmark.rb
<reponame>ankane/toucan<filename>benchmark.rb require "rubygems" require "bundler/setup" require "benchmark" require_relative "toucan" toucan = Toucan.new bm = Benchmark.measure do # 12x incr (= 12000 incr/sec) # can get 30000 incr/sec with node 1000.times do toucan.add_event(Time.now.to_i, "url", ["com", "amazon", "music"], 1) end end puts bm.real bm = Benchmark.measure do # generate 4000 graphs per sec 4000.times do toucan.minute_counts("url", ["com"]) end end puts bm.real
hkleindl/list-app-backend
app/models/user.rb
<gh_stars>0 class User < ApplicationRecord has_secure_password has_many :lists validates :username, presence: true end
hkleindl/list-app-backend
db/seeds.rb
# 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) 10.times do username = "#{Faker::Color.unique.color_name}_#{Faker::Creature::Animal.unique.name}" username = username.tr(" ", "_") User.create(username: username, password: "password") end User.all.each do |user| 3.times do list_name = Faker::Hipster.word.capitalize user.lists.create(name: list_name) end end List.all.each do |list| 6.times do content = Faker::Hipster.sentence list.items.create(content: content) end end
hkleindl/list-app-backend
app/controllers/api/v1/lists_controller.rb
<reponame>hkleindl/list-app-backend<filename>app/controllers/api/v1/lists_controller.rb class Api::V1::ListsController < ApplicationController before_action :set_list, only: [:show, :update, :destroy] # GET /lists def index if logged_in? @lists = current_user.lists render json: ListSerializer.new(@lists) else render json: { notice: "You must be logged in" } end end # GET /lists/1 def show render json: @list end # POST /lists def create @list = List.new(list_params) if @list.save render json: @list, status: :created, location: @list else render json: @list.errors, status: :unprocessable_entity end end # PATCH/PUT /lists/1 def update if @list.update(list_params) render json: @list else render json: @list.errors, status: :unprocessable_entity end end # DELETE /lists/1 def destroy @list.destroy end private # Use callbacks to share common setup or constraints between actions. def set_list @list = List.find(params[:id]) end # Only allow a trusted parameter "white list" through. def list_params params.require(:list).permit(:name) end end
hkleindl/list-app-backend
app/serializers/item_serializer.rb
class ItemSerializer include FastJsonapi::ObjectSerializer attributes :content, :is_complete # belongs_to :list, record_type: :list end
hkleindl/list-app-backend
app/models/list.rb
<reponame>hkleindl/list-app-backend<filename>app/models/list.rb class List < ApplicationRecord belongs_to :user has_many :items end
hkleindl/list-app-backend
app/serializers/list_serializer.rb
class ListSerializer include FastJsonapi::ObjectSerializer attributes :name, :items # belongs_to :user, record_type: :user # has_many :items end
kbredemeier/elastic_adatper
spec/unit/document_type_spec.rb
<reponame>kbredemeier/elastic_adatper require "spec_helper" module ElasticAdapter describe DocumentType do let(:mappings) do { name: { type: "string", index_analyzer: "shingle_analyzer" } } end let(:name) { "test_index" } let(:subject) { DocumentType.new(name, mappings) } describe "#initialize" do it "assigns the mappings" do expect(subject.instance_variable_get('@mappings')).to be mappings end it "assigns the name" do expect(subject.instance_variable_get('@name')).to be name end end describe "getter" do describe "name" do it "returns the name" do expect(subject.name).to eq name end end describe "mappings" do it "returns the mappings" do expect(subject.mappings).to eq mappings end end end end end
kbredemeier/elastic_adatper
elastic_adapter.gemspec
<filename>elastic_adapter.gemspec # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'elastic_adapter/version' Gem::Specification.new do |spec| spec.name = "elastic_adapter" spec.version = ElasticAdapter::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = %q{Repository like access to elasticseach indices} spec.description = %q{Repository like access to elasticseach indices} spec.homepage = "https://github.com/kbredemeier/elastic_adapter" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_dependency "elasticsearch", "~> 1.0.12" spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.1.0" spec.add_development_dependency "vcr", "~> 2.9.3" spec.add_development_dependency "webmock", "~> 1.20.4" spec.add_development_dependency "pry-byebug", "~> 3.0.1" spec.add_development_dependency "yard", "~> 0.8.7.6" spec.add_development_dependency "codeclimate-test-reporter" end
kbredemeier/elastic_adatper
spec/integration/index/suggest_spec.rb
<reponame>kbredemeier/elastic_adatper<filename>spec/integration/index/suggest_spec.rb<gh_stars>0 require_relative"./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#suggest", :vcr do before :all do create_test_index doc1 = {id: 1, foo: "bar", foo_suggest: {input: "bar"}} doc2 = {id: 2, foo: "zoo", foo_suggest: {input: "zoo"}} index_documents([doc1, doc2]) end after :all do delete_test_index end context "query 'ba'" do let(:query) do { foo_suggest: { text: "ba", completion: { field: "foo_suggest" } } } end let(:response) { subject.suggest(query) } it "returns bar" do expect(response['foo_suggest'].first['options'].first['text']).to eq 'bar' end end end end end
kbredemeier/elastic_adatper
examples/basic_usage.rb
<filename>examples/basic_usage.rb require "elastic_adapter" mappings = { product: { properties: { name: { type: "string", index_analyzer: "simple", search_analyzer: "simple" }, name_suggest: { type: "completion" }, price: { type: "float", index: "not_analyzed" } } } } settings = { number_of_shards: 1 } document_type = ElasticAdapter::DocumentType.new("product", mappings) index = ElasticAdapter::Index.new( name: "product_index", url: "http://localhost:9200", log: true, settings: settings, document_type: document_type ) # Creating an Index response = index.create_index response.inspect # => "{:acknowledged=>true}" response.class # => ElasticAdapter::Response response.success? # => true # Indexing doc1 = { id: 1, name: "foo", name_suggest: "foo", price: 11.12 } doc2 = { id: 2, name_suggest: "bar", suggest: "bar", price: 1.12 } response = index.index(doc1) response.inspect # => "{:index=>\"product_index\", :type=>\"product\", :id=>\"1\", :version=>1, :created=>true}" response.class # => ElasticAdapter::Response response.success? # => true response = index.index(doc2) response.inspect # => "{:index=>\"product_index\", :type=>\"product\", :id=>\"2\", :version=>1, :created=>true}" response.class # => ElasticAdapter::Response response.success? # => true sleep 3 # Query validation query = { query: { match_all: {} } } response = index.validate(query) response.inspect # => "true" response.class # => ElasticAdapter::Decoration::ValidationResponse query = { foo: { match_all: {} } } response = index.validate(query) response.inspect # => "false" response.class # => ElasticAdapter::Decoration::ValidationResponse # Count documents response = index.count(query) response.inspect # => "{:exception=>#<Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {\"count\":0,\"_shards\":{\"total\":1,\"successful\":0,\"failed\":1,\"failures\":[{\"index\":\"product_index\",\"shard\":0,\"reason\":\"BroadcastShardOperationFailedException[[product_index][0] ]; nested: QueryParsingException[[product_index] request does not support [foo]]; \"}]}}>}" response.class # => ElasticAdapter::Response # Get documents response = index.get(1) response.inspect # => "{:id=>\"1\", :name=>\"foo\", :name_suggest=>\"foo\", :price=>11.12}" response.class # => ElasticAdapter::Decoration::HitDecorator # Search documents response = index.search(query) response.inspect # => "{:exception=>#<Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {\"error\":\"SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures {[XRKX3VOdSDyg0HVSm3_Wiw][product_index][0]: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\\\"foo\\\":{\\\"match_all\\\":{}}}]]]; nested: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [No parser for element [foo]]]; }]\",\"status\":400}>}" response.class # => ElasticAdapter::Response query = {query: {match: {name: "foo"}}} response = index.search(query) response.inspect # => "{:exception=>#<Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {\"error\":\"SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures {[XRKX3VOdSDyg0HVSm3_Wiw][product_index][0]: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\\\"foo\\\":{\\\"match_all\\\":{}}}]]]; nested: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [No parser for element [foo]]]; }]\",\"status\":400}>}" response.class # => ElasticAdapter::Response # Suggestions suggest_query = { product_suggest: { text: "fo", completion: { field: "name_suggest" } } } response = index.suggest(suggest_query) response.inspect # => "{:options=>[{:text=>\"foo\", :score=>1.0}]}" response.class # => ElasticAdapter::Decoration::SuggestionResponse # Deleting an Index response = index.delete_index response.inspect # => "{:acknowledged=>true}" response.class # => ElasticAdapter::Response response.success? # => true # Failing actions response = index.delete_index response.inspect # => "{:exception=>#<Elasticsearch::Transport::Transport::Errors::NotFound: [404] {\"error\":\"IndexMissingException[[product_index] missing]\",\"status\":404}>}" response.class # => ElasticAdapter::Response response.success? # => false # !> 2015-02-06 17:52:19 +0100: PUT http://localhost:9200/product_index [status:200, request:0.053s, query:n/a] # !> 2015-02-06 17:52:19 +0100: > {"mappings":{"product":{"properties":{"name":{"type":"string","index_analyzer":"simple","search_analyzer":"simple"},"name_suggest":{"type":"completion"},"price":{"type":"float","index":"not_analyzed"}}}},"settings":{"number_of_shards":1}} # !> 2015-02-06 17:52:19 +0100: < {"acknowledged":true} # !> 2015-02-06 17:52:19 +0100: PUT http://localhost:9200/product_index/product/1 [status:201, request:0.037s, query:n/a] # !> 2015-02-06 17:52:19 +0100: > {"name":"foo","name_suggest":"foo","price":11.12} # !> 2015-02-06 17:52:19 +0100: < {"_index":"product_index","_type":"product","_id":"1","_version":1,"created":true} # !> 2015-02-06 17:52:19 +0100: PUT http://localhost:9200/product_index/product/2 [status:201, request:0.005s, query:n/a] # !> 2015-02-06 17:52:19 +0100: > {"name_suggest":"bar","suggest":"bar","price":1.12} # !> 2015-02-06 17:52:19 +0100: < {"_index":"product_index","_type":"product","_id":"2","_version":1,"created":true} # !> 2015-02-06 17:52:22 +0100: GET http://localhost:9200/product_index/_validate/query?explain=true [status:200, request:0.006s, query:n/a] # !> 2015-02-06 17:52:22 +0100: > {"query":{"match_all":{}}} # !> 2015-02-06 17:52:22 +0100: < {"valid":true,"_shards":{"total":1,"successful":1,"failed":0},"explanations":[{"index":"product_index","valid":true,"explanation":"ConstantScore(*:*)"}]} # !> 2015-02-06 17:52:22 +0100: GET http://localhost:9200/product_index/_validate/query?explain=true [status:200, request:0.004s, query:n/a] # !> 2015-02-06 17:52:22 +0100: > {"foo":{"match_all":{}}} # !> 2015-02-06 17:52:22 +0100: < {"valid":false,"_shards":{"total":1,"successful":1,"failed":0},"explanations":[{"index":"product_index","valid":false,"error":"org.elasticsearch.index.query.QueryParsingException: [product_index] request does not support [foo]"}]} # !> 2015-02-06 17:52:22 +0100: GET http://localhost:9200/product_index/_count [status:400, request:0.005s, query:N/A] # !> 2015-02-06 17:52:22 +0100: > {"foo":{"match_all":{}}} # !> 2015-02-06 17:52:22 +0100: < {"count":0,"_shards":{"total":1,"successful":0,"failed":1,"failures":[{"index":"product_index","shard":0,"reason":"BroadcastShardOperationFailedException[[product_index][0] ]; nested: QueryParsingException[[product_index] request does not support [foo]]; "}]}} # !> 2015-02-06 17:52:22 +0100: [400] {"count":0,"_shards":{"total":1,"successful":0,"failed":1,"failures":[{"index":"product_index","shard":0,"reason":"BroadcastShardOperationFailedException[[product_index][0] ]; nested: QueryParsingException[[product_index] request does not support [foo]]; "}]}} # !> 2015-02-06 17:52:22 +0100: GET http://localhost:9200/product_index/product/1 [status:200, request:0.004s, query:n/a] # !> 2015-02-06 17:52:22 +0100: < {"_index":"product_index","_type":"product","_id":"1","_version":1,"found":true,"_source":{"name":"foo","name_suggest":"foo","price":11.12}} # !> 2015-02-06 17:52:22 +0100: GET http://localhost:9200/product_index/_search [status:400, request:0.007s, query:N/A] # !> 2015-02-06 17:52:22 +0100: > {"foo":{"match_all":{}}} # !> 2015-02-06 17:52:22 +0100: < {"error":"SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures {[XRKX3VOdSDyg0HVSm3_Wiw][product_index][0]: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"foo\":{\"match_all\":{}}}]]]; nested: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [No parser for element [foo]]]; }]","status":400} # !> 2015-02-06 17:52:22 +0100: [400] {"error":"SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures {[XRKX3VOdSDyg0HVSm3_Wiw][product_index][0]: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"foo\":{\"match_all\":{}}}]]]; nested: SearchParseException[[product_index][0]: from[-1],size[-1]: Parse Failure [No parser for element [foo]]]; }]","status":400} # !> 2015-02-06 17:52:22 +0100: POST http://localhost:9200/product_index/_suggest [status:200, request:0.004s, query:n/a] # !> 2015-02-06 17:52:22 +0100: > {"product_suggest":{"text":"fo","completion":{"field":"name_suggest"}}} # !> 2015-02-06 17:52:22 +0100: < {"_shards":{"total":1,"successful":1,"failed":0},"product_suggest":[{"text":"fo","offset":0,"length":2,"options":[{"text":"foo","score":1.0}]}]} # !> 2015-02-06 17:52:22 +0100: DELETE http://localhost:9200/product_index [status:200, request:0.014s, query:n/a] # !> 2015-02-06 17:52:22 +0100: < {"acknowledged":true} # !> 2015-02-06 17:52:22 +0100: DELETE http://localhost:9200/product_index [status:404, request:0.003s, query:N/A] # !> 2015-02-06 17:52:22 +0100: < {"error":"IndexMissingException[[product_index] missing]","status":404} # !> 2015-02-06 17:52:22 +0100: [404] {"error":"IndexMissingException[[product_index] missing]","status":404}
kbredemeier/elastic_adatper
spec/integration/index/count_spec.rb
require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#count", :vcr do context "empty index" do before :all do create_test_index end after :all do delete_test_index end before { @result = subject.count } it "returns the amount of all documents" do expect(@result['count']).to eq 0 end end context "not empty index" do before :all do create_test_index index_documents foo: "bar" end after :all do delete_test_index end before { @result = subject.count } it "returns 1" do expect(@result['count']).to eq 1 end end end end end
kbredemeier/elastic_adatper
spec/integration/index/shared_context.rb
<gh_stars>0 require "spec_helper" RSpec.shared_context "index context" do let(:name) { "test_index" } let(:mappings) do { test_index: { properties: { foo: { type: "string", foo_suggest: { type: "completion" } } } } } end let(:document_type) do OpenStruct.new(name: "test_doc", mappings: mappings) end let(:settings) { { number_of_shards: 1 } } let(:log) { true } let(:url) { "http://localhost:9200"} let(:bar_doc) { { id: 1, foo: "bar", foo_suggest: {input: "bar"} } } let(:zoo_doc) { { id: 2, foo: "zoo", foo_suggest: {input: "zoo"} } } subject do ElasticAdapter::Index.new( name: name, settings: settings, document_type: document_type, url: url, log: log ) end end
kbredemeier/elastic_adatper
spec/unit/elastic_adapter_spec.rb
require "spec_helper" module ElasticAdapter end
kbredemeier/elastic_adatper
lib/elastic_adapter/document_type.rb
<reponame>kbredemeier/elastic_adatper<gh_stars>0 # rubocop:disable Metrics/LineLength module ElasticAdapter # This class is intended to hold information about # a document in an elasticsearch index # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping.html Elasticsearch Mappings # # @example # document_type = ElasticAdatper::DocumentType.new("test_doc", { # test_doc: { # properties: { # name: { # type: "string" # } # } # } # }) # # @attr_reader [String] name the name of the document # @attr_reader [Hash] mappings the mappings for the document class DocumentType attr_reader :name, :mappings # @param [String] name # @param [Hash] mappings def initialize(name, mappings) @name = name @mappings = mappings end end end
kbredemeier/elastic_adatper
spec/integration/index/unit_spec.rb
<filename>spec/integration/index/unit_spec.rb require_relative "./shared_context.rb" module ElasticAdapter describe Index do describe "unit specs" do include_context "index context" describe "#initialize" do it "assigns the name" do expect(subject.instance_variable_get('@name')).to be name end it "assigns the settings" do expect(subject.instance_variable_get('@settings')).to be settings end it "assigns the document_type" do expect(subject.instance_variable_get('@document_type')).to be document_type end it "assigns the url" do expect(subject.instance_variable_get('@url')).to be url end it "assigns the log" do expect(subject.instance_variable_get('@log')).to be log end end describe "getter" do describe "name" do it "returns the name" do expect(subject.name).to eq name end end describe "settings" do it "returns the settings" do expect(subject.settings).to eq settings end end describe "document_type" do it "returns the document_type" do expect(subject.document_type).to eq document_type end end describe "url" do it "returns the url" do expect(subject.url).to eq url end end describe "log" do it "returns the log" do expect(subject.log).to eq log end end describe "client" do it "returns the client" do expect(subject.client).to be_a ::Elasticsearch::Transport::Client end end end end end end
kbredemeier/elastic_adatper
spec/support/index_helper.rb
<reponame>kbredemeier/elastic_adatper module IndexHelper WAIT_TIME = 3 def test_index(name = "test_index", options = {}) params = { name: name, url: "http://localhost:9200", log: true, settings: {}, document_type: OpenStruct.new( name: "test_doc", mappings: { test_doc: { properties: { foo: { type: "string" }, foo_suggest: { type: "completion" } } } } ) }.merge(options) ElasticAdapter::Index.new(params) end def create_test_index(options = {}) prefix = options.fetch(:prefix, "") cassette_name = prefix + vcr_cassette_name_for(self.class.metadata) VCR.use_cassette cassette_name do test_index("test_index", options).create_index.tap { sleep WAIT_TIME if ENV["RECORDING"] } end end def delete_test_index(options = {}) prefix = options.fetch(:prefix, "") cassette_name = prefix + vcr_cassette_name_for(self.class.metadata) VCR.use_cassette cassette_name do test_index("test_index", options).delete_index # .tap { sleep 1 if ENV["RECORDING"] } end end def index_documents(documents, options = {}) prefix = options.fetch(:prefix, "") cassette_name = prefix + vcr_cassette_name_for(self.class.metadata) documents = [documents] unless documents.is_a? Array VCR.use_cassette cassette_name do documents.each do |document| test_index("test_index", options).index(document).tap { sleep WAIT_TIME if ENV["RECORDING"] } end end end def wait(time = WAIT_TIME) sleep time if ENV["RECORDING"] end # Taken from https://github.com/vcr/vcr/blob/bbf43f2cd4cc18b450fb37bcb32aa9d427d4235e/lib/vcr/test_frameworks/rspec.rb # def vcr_cassette_name_for(metadata) description = metadata[:description] example_group = if metadata.key?(:example_group) metadata[:example_group] else metadata[:parent_example_group] end if example_group [vcr_cassette_name_for(example_group), description].join('/') else description end end end
kbredemeier/elastic_adatper
lib/elastic_adapter/index.rb
module ElasticAdapter # This class encapsulates the access to a Elasticsearch::Transport::Client # and provides an implementation of the repository pattern # # @attr_reader [String] name the name of the index # @attr_reader [Hash] settings the index settings # @attr_reader [DocumentType] document_type a DocumentType # with the document name and it's mappings # @attr_reader [String] url the url to elasticsearch # @attr_reader [Boolean] log print degub log to $stdout # @attr_reader [Client] client the client who # handles the communication with elasticsearch # # @example Initialization # index = ElasticAdapter::Index.new( # name: "test_index", # settings: { number_of_shards: 1 }, # document_type: ElasticAdapter::DocumentType.new("test_doc", mappings: { # test_doc: { # properties: { # foo: { type: "string" } # } # } # } # ), # url: "localhost:9200", # log: true # ) class Index attr_reader :name, :settings, :document_type, :url, :log, :client # @param [Hash] params # @option params [String] :name required # @option params [Hash] :settings required # @option params [DocumentType] :document_type required # @option params [String] :url required # @option params [Boolean] :log required # @option params [Client] client optional: A client. Defaults to # Elasticsearch#Transport#Client def initialize(params) @name = params.fetch(:name) @settings = params.fetch(:settings) @document_type = params.fetch(:document_type) @url = params.fetch(:url) @log = params.fetch(:log) @client = params.fetch :client do Elasticsearch::Client.new(url: url, log: log) end self end # Creates the index with it's settings and mappings # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html Elasticsearch create index # # @return [Hash] def create_index client.indices.create( index: name, body: { mappings: document_type.mappings, settings: settings } ) end # Deletes the index # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-delete-index.html Elasticsearch delete index # # @return [Hash] def delete_index client.indices.delete index: name end # Returns the document count for the index # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-count.html#search-count Elasticsearch count api # # @param [Hash] query a query to count the documents for a given query. Defaults to match all # @return [Hash] the count def count(query = { query: { match_all: {} } }) client.count index: name, body: query end # Indexes a Hash or anything that responds to to_hash as a document # in the index # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html Elasticsearch index api # # @example # test_index = ElasticAdapter::Index.new(...) # test_index.index(id: 1, name: "foo") # # @param [Hash] document # @return [Hash] def index(document) doc = document.to_hash.merge({}) params = { index: name, id: doc.delete(:id), type: document_type.name, body: doc } client.index(params) end # Returns the document with the given id from the index # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-get.html Elasticsearch get api # # @param [Integer] id # @return [ElasticAdapter::HitDecorator] def get(id) client.get( index: name, type: document_type.name, id: id ) end # Searches the index for documents matching the passed query. # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search.html Elasticsearch search apis # # @example # test_index = ElasticAdatper::Index.new(...) # test_index.seach(query: {match: {foo: "bar"}}) # # @param [Hash] query # @return [Hash] def search(query) client.search( index: name, body: query ) end # Searches the index for suggestions for the passed suggest query # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters.html Elasticsearch suggesters # # @example # test_index = ElasticAdatper::Index.new(...) # test_index.seach(name_suggestions: {text: "foo", completion: {field: "name"}}) # # @param [Hash] query # @return [Hash] def suggest(query) client.suggest( index: name, body: query ) end # Validates the passed query # # @see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-validate.html Elasticsearch validate api # # @param [Hash] query # @return [Hash] def validate(query) client.indices.validate_query( index: name, explain: true, body: query ) end # Executes a search request and returns the response # # @param [Hash] query # @return [Hash] def aggregate(query) client.search( index: name, body: query ) end end end
kbredemeier/elastic_adatper
spec/integration/index/validate_spec.rb
require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#validate", :vcr do before :all do create_test_index end after :all do delete_test_index end context "invalid query" do let(:query) do { asd: "[[[ BOOM! ]]]" } end let(:response) { subject.validate(query) } describe "valid?" do it "is false" do expect(response['valid']).to be false end end end context "valid query" do let(:query) {{ query: { match_all: {} } }} let(:response) { subject.validate(query) } it "is true" do expect(response['valid']).to eq true end end end end end
kbredemeier/elastic_adatper
spec/integration/index/search_spec.rb
require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#search", :vcr do before :all do create_test_index index_documents(id: 1, foo: "bar", foo_suggest: {input: "bar"}) index_documents(id: 2, foo: "zoo", foo_suggest: {input: "zoo"}) end after :all do delete_test_index end context "match_all" do it "returns all documents" do result = subject.search({query: {match_all: {}}}) expect(result['hits']['total']).to eq 2 end end context "zoo" do let(:response) { subject.search(query: {match: {foo: "zoo"}})} it "returns one document" do expect(response['hits']['total']).to eq 1 end it "returns the wanted document" do expect(response['hits']['hits'].first['_id']).to eq '2' expect(response['hits']['hits'].first['_source']['foo']).to eq 'zoo' end end end end end
kbredemeier/elastic_adatper
spec/integration/index/aggregation_spec.rb
<filename>spec/integration/index/aggregation_spec.rb require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#aggregate", :vcr do before :all do create_test_index index_documents foo: "bar", group: "A" index_documents foo: "baz", group: "A" index_documents foo: "boo", group: "B" end after :all do delete_test_index end describe "response" do let(:query) {{ aggs: { group: { terms: { field: "group" } } } }} before do @response = subject.aggregate(query) end it "has a aggregation" do expect(@response['aggregations']).not_to be_empty end end end end end
kbredemeier/elastic_adatper
lib/elastic_adapter.rb
<gh_stars>0 require "elasticsearch" require "elastic_adapter/version" require "elastic_adapter/document_type" require "elastic_adapter/index" begin require "pry" rescue LoadError end module ElasticAdapter end
kbredemeier/elastic_adatper
spec/integration/index/get_spec.rb
<reponame>kbredemeier/elastic_adatper<filename>spec/integration/index/get_spec.rb require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#get", :vcr do context "document exists" do let(:document) { {id: "1", foo: "bar"} } before :all do create_test_index index_documents(foo: "bar", id: 1) end after :all do delete_test_index end let(:response) { subject.get(1) } describe "response" do describe "document" do it "returns the document" do expected = { '_index' => 'test_index', '_type' => "test_doc", '_id' => "1", '_version' => 1, 'found' => true, '_source' => { 'foo' => 'bar' } } expect(response).to eq expected end end end end end end end
kbredemeier/elastic_adatper
lib/elastic_adapter/version.rb
module ElasticAdapter VERSION = "0.2.0" end
kbredemeier/elastic_adatper
spec/integration/index/index_spec.rb
require_relative "./shared_context.rb" module ElasticAdapter describe Index do include_context "index context" describe "#index", :vcr do context "new document" do let(:document) { { foo: "bar" } } before :all do create_test_index end after :all do delete_test_index end it "indexes a document" do subject.index(document) response = subject.count expect(response['count']).to eq 1 end end end end end
kbredemeier/elastic_adatper
spec/unit/index_spec.rb
require "spec_helper" module ElasticAdapter describe Index do let(:name) { "test_index" } let(:mappings) do { test_index: { properties: { foo: { type: "string", foo_suggest: { type: "completion" } } } } } end let(:document_type) do OpenStruct.new(name: "test_doc", mappings: mappings) end let(:settings) { { number_of_shards: 1 } } let(:log) { true } let(:url) { "http://localhost:9200"} let(:indices) { double("indices") } let(:client) { double("client") } subject do ElasticAdapter::Index.new( name: name, settings: settings, document_type: document_type, url: url, log: log, client: client ) end before do allow(client).to receive(:indices).and_return(indices) end let(:query) {{ query: { match_all: {} } }} describe "#initialize" do it "takes a hash as arguments" do expect { subject }.not_to raise_error end end describe "#name" do it "returns the name" do expect(subject.name).to be name end end describe "#settings" do it "returns the settings" do expect(subject.settings).to be settings end end describe "#document_type" do it "returns the document type" do expect(subject.document_type).to be document_type end end describe "#url" do it "returns the url" do expect(subject.url).to be url end end describe "#log" do it "returns log" do expect(subject.log).to be log end end describe "client" do it "returns a client" do expect(subject.client).to be client end end describe "#create_index" do it "creates the index" do expect(indices).to receive(:create) .with( index: name, body: { mappings: document_type.mappings, settings: settings } ) subject.create_index end end describe "#delete_index" do it "deletes the index" do expect(indices).to receive(:delete).with(index: name) subject.delete_index end end describe "#count" do it "does a count request" do expect(client).to receive(:count).with(index: name, body: query) subject.count(query) end it "returns the response" do expect(client).to receive(:count).and_return({}) result = subject.count(query) expect(result).to eq({}) end end describe "#index" do let(:doc) {{ id: 1, foo: "bar" }} it "indexes the document" do expect(client).to receive(:index) .with( index: name, id: 1, type: document_type.name, body: { foo: "bar" } ) subject.index(doc) end it "returns the response" do expect(client).to receive(:index).and_return({}) result = subject.index(doc) expect(result).to eq({}) end end describe "#get" do it "does a get request" do expect(client).to receive(:get).with(index: name, type: document_type.name, id: 1) subject.get(1) end it "returns the response" do expect(client).to receive(:get).and_return({}) result = subject.get(1) expect(result).to eq({}) end end describe "#search" do it "does a search request" do expect(client).to receive(:search).with(index: name, body: query) subject.search(query) end it "returns the response" do expect(client).to receive(:search).and_return({}) result = subject.search(query) expect(result).to eq({}) end end describe "#suggest" do it "does a suggest request" do expect(client).to receive(:suggest).with(index: name, body: query) subject.suggest(query) end it "returns the response" do expect(client).to receive(:suggest).and_return({}) result = subject.suggest(query) expect(result).to eq({}) end end describe "#aggregate" do it "does a aggregate request" do expect(client).to receive(:search).with(index: name, body: query) subject.aggregate(query) end it "returns the response" do expect(client).to receive(:search).and_return({}) result = subject.aggregate(query) expect(result).to eq({}) end end describe "#validate" do it "does a validate request" do expect(indices).to receive(:validate_query).with(index: name, body: query, explain: true) subject.validate(query) end it "returns the response" do expect(indices).to receive(:validate_query).and_return({}) result = subject.validate(query) expect(result).to eq({}) end end end end
beplus/fastlane-plugin-versioning-ios
lib/fastlane/plugin/versioning_ios/helper/versioning_ios_helper.rb
module Fastlane module Helper class VersioningIosHelper require "shellwords" XCODEPROJ_TEST = "/tmp/fastlane/tests/versioning/Project.xcodeproj" def self.get_xcodeproj(xcodeproj) return Helper.test? ? XCODEPROJ_TEST : xcodeproj end def self.get_xcodeproj_path(xcodeproj) project_file = self.get_xcodeproj(xcodeproj) path = project_file ? File.join(project_file, "..") : "." return File.expand_path(path).shellescape end def self.get_version_command(xcodeproj) path = self.get_xcodeproj_path(xcodeproj) return [ "cd", path, "&&", "agvtool", "what-marketing-version", "-terse1" ].join(" ") end def self.set_version_command(xcodeproj, version) path = self.get_xcodeproj_path(xcodeproj) version = self.parse_version(version) return [ "cd", path, "&&", "agvtool", "new-marketing-version", version ].join(" ") end def self.get_build_number_command(xcodeproj) path = self.get_xcodeproj_path(xcodeproj) return [ "cd", path, "&&", "agvtool", "what-version", "-terse" ].join(" ") end def self.set_build_number_command(xcodeproj, build_number) path = self.get_xcodeproj_path(xcodeproj) agvtool_command = build_number ? "new-version -all #{self.parse_build_number(build_number)}" : "next-version -all" return [ "cd", path, "&&", "agvtool", agvtool_command ].join(" ") end def self.parse_version(version) # @todo SemVer check return version.to_s.strip end def self.parse_build_number(build_number) return build_number.to_s.strip end def self.is_agv_enabled(xcodeproj) # We do not want to run agvtool under tests to avoid # output about not having a project configured for AGV command_get = "#{self.get_version_command(xcodeproj)} > /dev/null 2>&1" unless Helper.test? agv_enabled = system(command_get) raise "Apple Generic Versioning (AGV) is not enabled." unless agv_enabled end end end end end
beplus/fastlane-plugin-versioning-ios
spec/versioning_ios_helper_spec.rb
<reponame>beplus/fastlane-plugin-versioning-ios<filename>spec/versioning_ios_helper_spec.rb require 'spec_helper' describe Fastlane::Helper::VersioningIosHelper do describe "Versioning iOS Helper" do it "should return path to Xcode project" do result = Fastlane::Helper::VersioningIosHelper.get_xcodeproj(nil) expect(result).to eq(Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST) end it "should return absolute folder with Xcode project" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST result = Fastlane::Helper::VersioningIosHelper.get_xcodeproj_path(xcodeproj) expect(result).to eq("/tmp/fastlane/tests/versioning") end it "should create the command for getting version" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST result = Fastlane::Helper::VersioningIosHelper.get_version_command(xcodeproj) expect(result).to eq("cd /tmp/fastlane/tests/versioning && agvtool what-marketing-version -terse1") end it "should create the command for setting new version" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST version = "1.23.4" result = Fastlane::Helper::VersioningIosHelper.set_version_command(xcodeproj, version) expect(result).to eq("cd /tmp/fastlane/tests/versioning && agvtool new-marketing-version #{version}") end it "should create the command for getting build number" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST result = Fastlane::Helper::VersioningIosHelper.get_build_number_command(xcodeproj) expect(result).to eq("cd /tmp/fastlane/tests/versioning && agvtool what-version -terse") end it "should create the command for setting new (increment) build number" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST build_number = nil result = Fastlane::Helper::VersioningIosHelper.set_build_number_command(xcodeproj, build_number) expect(result).to eq("cd /tmp/fastlane/tests/versioning && agvtool next-version -all") end it "should create the command for setting new (specific) build number" do xcodeproj = Fastlane::Helper::VersioningIosHelper::XCODEPROJ_TEST build_number = "17" result = Fastlane::Helper::VersioningIosHelper.set_build_number_command(xcodeproj, build_number) expect(result).to eq("cd /tmp/fastlane/tests/versioning && agvtool new-version -all #{build_number}") end end end
beplus/fastlane-plugin-versioning-ios
spec/ios_set_build_number_action_spec.rb
require 'spec_helper' describe Fastlane::Actions::IosSetBuildNumberAction do describe "Set Build Number" do before do copy_project_files_fixture end it "should increment Build Number and return its new value" do result = Fastlane::FastFile.new.parse('lane :test do ios_set_build_number end').runner.execute(:test) expect(result).to eq("18") end it "should set incremented Build Number to IOS_NEW_BUILD_NUMBER shared value" do Fastlane::FastFile.new.parse('lane :test do ios_set_build_number end').runner.execute(:test) expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::IOS_NEW_BUILD_NUMBER]).to eq("18") end it "should set specific Build Number and return its new value" do result = Fastlane::FastFile.new.parse('lane :test do ios_set_build_number(build_number: 17) end').runner.execute(:test) expect(result).to eq("17") end it "should set specific Build Number to IOS_NEW_BUILD_NUMBER shared value" do Fastlane::FastFile.new.parse('lane :test do ios_set_build_number(build_number: 17) end').runner.execute(:test) expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::IOS_NEW_BUILD_NUMBER]).to eq("17") end after do remove_project_files_fixture end end end
beplus/fastlane-plugin-versioning-ios
lib/fastlane/plugin/versioning_ios/version.rb
module Fastlane module VersioningIos VERSION = "0.1.0" end end
beplus/fastlane-plugin-versioning-ios
lib/fastlane/plugin/versioning_ios/actions/ios_set_version.rb
module Fastlane module Actions module SharedValues IOS_NEW_VERSION = :IOS_NEW_VERSION end class IosSetVersionAction < Action # More information about how to set up your project and how it works: # https://developer.apple.com/library/ios/qa/qa1827/_index.html # Attention: This is NOT the Version - but the Build Number def self.run(params) xcodeproj = params[:xcodeproj] version = params[:version] command_get = Helper::VersioningIosHelper.get_version_command(xcodeproj) command_set = Helper::VersioningIosHelper.set_version_command(xcodeproj, version) Helper::VersioningIosHelper.is_agv_enabled(xcodeproj) if Helper.test? `#{command_set}` new_version = `#{command_get}` else (Actions.sh command_set) new_version = (Actions.sh command_get) end new_version = Helper::VersioningIosHelper.parse_version(new_version) UI.success("👍 Version has been set to: #{new_version}") # Store the Version in the shared hash Actions.lane_context[SharedValues::IOS_NEW_VERSION] = new_version end def self.description "Set the Version of your iOS project" end def self.details [ "This action will set the new Version on your iOS project.", "You have to set up your Xcode project to use AGV. For more info:", "https://developer.apple.com/library/ios/qa/qa1827/_index.html" ].join(' ') end def self.available_options [ FastlaneCore::ConfigItem.new(key: :version, env_name: "FL_IOS_SET_VERSION_VERSION", description: "Change to a specific Version", optional: true, is_string: true), FastlaneCore::ConfigItem.new(key: :xcodeproj, env_name: "FL_IOS_SET_VERSION_XCODEPROJ", description: "(optional) Specify the path to your main Xcode project if it isn't in the project root directory", optional: true, verify_block: proc do |value| UI.user_error!("Please specify the path to the project, not workspace") if value.end_with? ".xcworkspace" UI.user_error!("Could not find Xcode project") unless File.exist?(value) end) ] end def self.output [ ['IOS_NEW_VERSION', 'The new Version of your iOS project'] ] end def self.return_value "The new Version of your iOS project" end def self.authors ["<NAME>"] end def self.is_supported?(platform) [:ios].include? platform end def self.example_code [ 'ios_set_version( version: "1.23.4" # Set a specific version )', 'ios_set_version( version: "1.23.4", # Set a specific version xcodeproj: "/path/to/Project.xcodeproj" # Xcode project is not in the project root directory )' ] end end end end
beplus/fastlane-plugin-versioning-ios
spec/spec_helper.rb
<filename>spec/spec_helper.rb $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'simplecov' # SimpleCov.minimum_coverage 95 SimpleCov.start # This module is only used to check the environment is currently a testing env module SpecHelper end require 'fastlane' # to import the Action super class require 'fastlane/plugin/versioning_ios' # import the actual plugin Fastlane.load_actions # load other actions (in case your plugin calls other actions or shared values) def copy_project_files_fixture FileUtils.mkdir_p("/tmp/fastlane/tests/versioning") source = "./spec/fixtures" destination = "/tmp/fastlane/tests/versioning" FileUtils.copy_entry(source, destination) end def remove_project_files_fixture FileUtils.rm_rf("/tmp/fastlane/tests/versioning") end
beplus/fastlane-plugin-versioning-ios
lib/fastlane/plugin/versioning_ios/actions/ios_get_version.rb
<reponame>beplus/fastlane-plugin-versioning-ios module Fastlane module Actions module SharedValues IOS_VERSION = :IOS_VERSION end class IosGetVersionAction < Action # More information about how to set up your project and how it works: # https://developer.apple.com/library/ios/qa/qa1827/_index.html # Attention: This is NOT the Version - but the Build Number def self.run(params) xcodeproj = params[:xcodeproj] command_get = Helper::VersioningIosHelper.get_version_command(xcodeproj) Helper::VersioningIosHelper.is_agv_enabled(xcodeproj) version = Helper.test? ? `#{command_get}` : (Actions.sh command_get) version = Helper::VersioningIosHelper.parse_version(version) UI.success("👍 Current Version is: #{version}") # Store the Version in the shared hash Actions.lane_context[SharedValues::IOS_VERSION] = version end def self.description "Get the Version of your iOS project" end def self.details [ "This action will return current Version of your iOS project.", "You have to set up your Xcode project to use AGV. For more info:", "https://developer.apple.com/library/ios/qa/qa1827/_index.html" ].join(' ') end def self.available_options [ FastlaneCore::ConfigItem.new(key: :xcodeproj, env_name: "FL_IOS_GET_VERSION_XCODEPROJ", description: "(optional) Specify the path to your main Xcode project if it isn't in the project root directory", optional: true, verify_block: proc do |value| UI.user_error!("Please specify the path to the project, not workspace") if value.end_with? ".xcworkspace" UI.user_error!("Could not find Xcode project") unless File.exist?(value) end) ] end def self.output [ ['IOS_VERSION', 'The Version of your iOS project'] ] end def self.return_value "The Version of your iOS project" end def self.authors ["<NAME>"] end def self.is_supported?(platform) [:ios].include? platform end def self.example_code [ 'build_number = ios_get_version # Xcode project is in the project root directory', 'build_number = ios_get_version(xcodeproj: "/path/to/Project.xcodeproj")' ] end end end end
beplus/fastlane-plugin-versioning-ios
lib/fastlane/plugin/versioning_ios/actions/ios_set_build_number.rb
module Fastlane module Actions module SharedValues IOS_NEW_BUILD_NUMBER = :IOS_NEW_BUILD_NUMBER end class IosSetBuildNumberAction < Action # More information about how to set up your project and how it works: # https://developer.apple.com/library/ios/qa/qa1827/_index.html # Attention: This is NOT the Version - but the Build Number def self.run(params) xcodeproj = params[:xcodeproj] build_number = params[:build_number] command_get = Helper::VersioningIosHelper.get_build_number_command(xcodeproj) command_set = Helper::VersioningIosHelper.set_build_number_command(xcodeproj, build_number) Helper::VersioningIosHelper.is_agv_enabled(xcodeproj) if Helper.test? `#{command_set}` new_build_number = `#{command_get}` else (Actions.sh command_set) new_build_number = (Actions.sh command_get) end new_build_number = Helper::VersioningIosHelper.parse_build_number(new_build_number) UI.success("👍 Build Number has been set to: #{new_build_number}") # Store the Build Number in the shared hash Actions.lane_context[SharedValues::IOS_NEW_BUILD_NUMBER] = new_build_number end def self.description "Set the Build Number of your iOS project" end def self.details [ "This action will set the new Build Number on your iOS project.", "You have to set up your Xcode project to use AGV. For more info:", "https://developer.apple.com/library/ios/qa/qa1827/_index.html" ].join(' ') end def self.available_options [ FastlaneCore::ConfigItem.new(key: :build_number, env_name: "FL_IOS_SET_BUILD_NUMBER_BUILD_NUMBER", description: "Change to a specific Build Number", optional: true, is_string: false), FastlaneCore::ConfigItem.new(key: :xcodeproj, env_name: "FL_IOS_SET_BUILD_NUMBER_XCODEPROJ", description: "(optional) Specify the path to your main Xcode project if it isn't in the project root directory", optional: true, verify_block: proc do |value| UI.user_error!("Please specify the path to the project, not workspace") if value.end_with? ".xcworkspace" UI.user_error!("Could not find Xcode project") unless File.exist?(value) end) ] end def self.output [ ['IOS_NEW_BUILD_NUMBER', 'The new Build Number of your iOS project'] ] end def self.return_value "The new Build Number of your iOS project" end def self.authors ["<NAME>"] end def self.is_supported?(platform) [:ios].include? platform end def self.example_code [ 'ios_set_build_number # Automatically increment by one', 'ios_set_build_number( build_number: "17" # Set a specific number )', 'ios_set_build_number( build_number: "17", xcodeproj: "/path/to/Project.xcodeproj" # Xcode project is not in the project root directory )', 'build_number = ios_set_build_number # Save returned Build Number to a variable' ] end end end end
beplus/fastlane-plugin-versioning-ios
spec/ios_get_build_number_action_spec.rb
require 'spec_helper' describe Fastlane::Actions::IosGetBuildNumberAction do describe "Get Build Number" do before do copy_project_files_fixture end it "should return Build Number from Xcode project file" do result = Fastlane::FastFile.new.parse('lane :test do ios_get_build_number end').runner.execute(:test) expect(result).to eq("17") end it "should set Build Number to IOS_BUILD_NUMBER shared value" do Fastlane::FastFile.new.parse('lane :test do ios_get_build_number end').runner.execute(:test) expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::IOS_BUILD_NUMBER]).to eq("17") end after do remove_project_files_fixture end end end
beplus/fastlane-plugin-versioning-ios
spec/ios_set_version_action_spec.rb
require 'spec_helper' describe Fastlane::Actions::IosSetVersionAction do describe "Set Version" do before do copy_project_files_fixture end it "should set Version to specific value" do result = Fastlane::FastFile.new.parse('lane :test do ios_set_version(version: "2.34.5") end').runner.execute(:test) expect(result).to eq("2.34.5") end it "should set Version to IOS_NEW_VERSION shared value" do Fastlane::FastFile.new.parse('lane :test do ios_set_version(version: "2.34.5") end').runner.execute(:test) expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::IOS_NEW_VERSION]).to eq("2.34.5") end after do remove_project_files_fixture end end end
takamario/imgix-rails
lib/imgix/rails/tag.rb
require "imgix/rails/url_helper" require "action_view" class Imgix::Rails::Tag include Imgix::Rails::UrlHelper include ActionView::Helpers def initialize(path, source: nil, tag_options: {}, url_params: {}, srcset_options: {}) @path = path @source = source @tag_options = tag_options @url_params = url_params @srcset_options = srcset_options end protected def srcset(source: @source, path: @path, url_params: @url_params, srcset_options: @srcset_options, tag_options: @tag_options) params = url_params.clone width_tolerance = ::Imgix::Rails.config.imgix[:srcset_width_tolerance] min_width = @srcset_options[:min_width] max_width = @srcset_options[:max_width] widths = @srcset_options[:widths] disable_variable_quality = @srcset_options[:disable_variable_quality] options = { widths: widths, width_tolerance: width_tolerance, min_width: min_width, max_width: max_width, disable_variable_quality: disable_variable_quality} ix_image_srcset(@source, @path, params, options) end end
takamario/imgix-rails
lib/imgix/rails/url_helper.rb
module Imgix module Rails class ConfigurationError < StandardError; end module UrlHelper def ix_image_url(*args) validate_configuration! case args.size when 1 path = args[0] source = nil params = {} when 2 if args[0].is_a?(String) && args[1].is_a?(Hash) source = nil path = args[0] params = args[1] elsif args[0].is_a?(String) && args[1].is_a?(String) source = args[0] path = args[1] params = {} else raise RuntimeError.new("path and source must be of type String; params must be of type Hash") end when 3 source = args[0] path = args[1] params = args[2] else raise RuntimeError.new('path missing') end imgix_client(source).path(path).to_url(params).html_safe end protected def ix_image_srcset(*args) validate_configuration! case args.size when 1 path = args[0] source = nil params = {} when 2 if args[0].is_a?(String) && args[1].is_a?(Hash) source = nil path = args[0] params = args[1] elsif args[0].is_a?(String) && args[1].is_a?(String) source = args[0] path = args[1] params = {} else raise RuntimeError.new("path and source must be of type String; params must be of type Hash") end when 3 source = args[0] path = args[1] params = args[2] when 4 source = args[0] path = args[1] params = args[2] options = args[3] else raise RuntimeError.new('path missing') end imgix_client(source).path(path).to_srcset(options: options, **params).html_safe end private def validate_configuration! imgix = ::Imgix::Rails.config.imgix if imgix.slice(:source, :sources).size != 1 raise ConfigurationError.new("Exactly one of :source, :sources is required") end if imgix[:source] unless imgix[:source].is_a?(String) raise ConfigurationError.new("imgix source must be a String.") end end if imgix[:sources] unless imgix[:sources].is_a?(Hash) raise ConfigurationError.new(":sources must be a Hash") end end end def imgix_client(source) begin return imgix_clients.fetch(source) rescue KeyError raise RuntimeError.new("Unknown source '#{source}'") end end def imgix_clients return @imgix_clients if @imgix_clients imgix = ::Imgix::Rails.config.imgix opts = { library_param: "rails", library_version: Imgix::Rails::VERSION, use_https: true, } if imgix[:source].is_a?(String) opts[:host] = imgix[:source] end if imgix.has_key?(:include_library_param) opts[:include_library_param] = imgix[:include_library_param] end if imgix.has_key?(:use_https) opts[:use_https] = imgix[:use_https] end sources = imgix[:sources] || { imgix[:source] => imgix[:secure_url_token] } @imgix_clients = {} sources.map do |source, token| opts[:host] = source opts[:secure_url_token] = token @imgix_clients[source] = ::Imgix::Client.new(opts) end default_source = imgix[:default_source] || imgix[:source] if default_source @imgix_clients[nil] = @imgix_clients.fetch(default_source) end @imgix_clients end end end end
railsrumble/r13-team-46
app/helpers/tasks_helper.rb
<filename>app/helpers/tasks_helper.rb module TasksHelper def task_summary(task) result = [ task.time_expression, "I want to", task.action ].join(" ") truncate(result, length: 50) end def task_scheduled_class(task) 'not-scheduled' unless task.recurrence.try(:next_at) end end
railsrumble/r13-team-46
lib/tasks/guest.rake
<filename>lib/tasks/guest.rake namespace :guest do desc "Setup Guest User" task reset: :environment do User.where(is_guest: true).destroy_all guest = User.create( email: "<EMAIL>", password: "<PASSWORD>", is_guest: true ) CreateTask.create({ user_id: guest.id, time_expression: "Every Monday", action: "go to the gym." }) CreateTask.create({ user_id: guest.id, time_expression: "Every month", action: "do the cleaning." }) CreateTask.create({ user_id: guest.id, time_expression: "Every day", action: "do the homework." }) CreateTask.create({ user_id: guest.id, time_expression: "Every Christmas", action: "make a cheesecake." }) CreateTask.create({ user_id: guest.id, time_expression: "Every 6 months", action: "update my resume." }) CreateTask.create({ user_id: guest.id, time_expression: "Every 5th May", action: "buy flowers for my girl." }) unscheduled = CreateTask.create({ user_id: guest.id, time_expression: "Every day", action: "buy milk." }) unscheduled.recurrence.update_attribute(:next_at, nil) end end
railsrumble/r13-team-46
spec/models/task_spec.rb
<reponame>railsrumble/r13-team-46 require 'model_spec_helper' describe Task do it { should validate_presence_of(:action) } it { should validate_presence_of(:time_expression) } it { should validate_presence_of(:user_id) } context "using repository" do let(:attributes) { build_attributes_for(:task) } class TimeZoneConverter def self.convert(moment, user) moment end end before do @now = Time.local(2013, 10, 19, 0, 0, 0) Timecop.freeze(@now) end it 'creates task and recurrence' do task = CreateTask.create(attributes) recurrence = task.recurrence expect(recurrence).to be_present expect(recurrence.expression).to eq("day") expect(recurrence.starting_at).to eq(@now) expect(recurrence.next_at).to eq(@now.advance(days: 1)) expect(recurrence.until_at).to be_nil end end end
railsrumble/r13-team-46
app/services/handle_recurrences.rb
class HandleRecurrences def self.perform new.perform end def recurrences Recurrence.ready end def perform recurrences.each do |recurrence| handle_recurrence(recurrence) end end def handle_recurrence(recurrence) recurrence_hooks.each do |hook| send(hook, recurrence) end end def recurrence_hooks [ :send_mail_notification, :set_last_at, :reset_next_at ] end def send_mail_notification(recurrence) RecurrenceMailer.notify(recurrence.user, recurrence.task).deliver end def set_last_at(recurrence) recurrence.update_attributes(last_at: recurrence.next_at) end def reset_next_at(recurrence) recurrence.update_attributes(next_at: nil) end end
railsrumble/r13-team-46
app/helpers/recurrences_helper.rb
<filename>app/helpers/recurrences_helper.rb module RecurrencesHelper def recurrence_human_next_at(recurrence) recurrence_human_date(recurrence, :next_at, "Not planned yet") end def recurrence_human_last_at(recurrence) recurrence_human_date(recurrence, :last_at, "Not reminded yet") end def recurrence_human_date(recurrence, field, empty_message) date = recurrence.send(field) if date.present? content_tag :span, class: "popup", data: { tip: human_date(date) } do distance_of_time_in_words(Time.zone.now, date) end else content_tag :span do empty_message end end end end
railsrumble/r13-team-46
app/repositories/create_repository.rb
class CreateRepository class << self %w( create create! ).each do |sym| define_method sym do |*args| new.send(sym, *args) end end end def klass self.class.name.gsub(/^Create/, '').constantize end %w( create create! ).each do |sym| define_method sym do |hash| sanitize_attributes!(hash) klass.send(sym, hash).tap do |obj| after_create(obj) if obj.persisted? end end end def after_create(obj) after_create_hooks.each do |klass| klass.new(obj).perform end end def sanitize_attributes!(hash) end def after_create_hooks [] end end
railsrumble/r13-team-46
app/models/ability.rb
class Ability include CanCan::Ability def initialize(user) user ||= User.new cannot :manage, Task can :manage, Task, user_id: user.id end end
railsrumble/r13-team-46
spec/support/devise.rb
<filename>spec/support/devise.rb RSpec.configure do |config| config.include Devise::TestHelpers, type: :controller end module DeviseHelperMethods include Warden::Test::Helpers def sign_in(user) login_as user, scope: :user end end RSpec.configuration.include DeviseHelperMethods, type: :feature
railsrumble/r13-team-46
app/models/user.rb
<filename>app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :omniauthable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me, :provider, :uid, :time_zone, :is_guest has_many :tasks, dependent: :destroy include ActiveRecordHelpers end
railsrumble/r13-team-46
spec/model_spec_helper.rb
require 'unit_spec_helper' require 'active_record' require 'devise' db_yml_file = File.expand_path('config/database.yml') template = ERB.new(File.new(db_yml_file).read, nil, "%") db_config = YAML.load(template.result(binding)) ActiveRecord::Base.establish_connection(db_config['test']) require File.join(RAILS_ROOT, "config/initializers/devise.rb") require File.join(RAILS_ROOT, "spec/support/database_cleaner.rb") autoload_paths = ActiveSupport::Dependencies.autoload_paths %w(app/models app/concerns).each do |path| autoload_paths.push(path) unless autoload_paths.include?(path) end if require 'factory_girl' require File.join(RAILS_ROOT, "spec/support/factory_girl.rb") FactoryGirl.find_definitions end
railsrumble/r13-team-46
app/repositories/update_task.rb
class UpdateTask < Struct.new(:task) def perform(attributes) if task.update_attributes(attributes) SyncTaskRecurrence.new(task).perform end end end
railsrumble/r13-team-46
spec/factories/recurrences.rb
FactoryGirl.define do factory :recurrence do task auto_schedule false expression "day" next_at "2013-10-19 10:56:03" starting_at "2013-10-19 10:56:03" until_at "2013-10-21 10:56:03" end end
railsrumble/r13-team-46
spec/factories/tasks.rb
FactoryGirl.define do factory :task do user action "code hard" time_expression "every day" end end
railsrumble/r13-team-46
spec/support/capybara.rb
require 'capybara/rspec' Capybara.javascript_driver = :webkit class WarningSuppressor WARNINGS = [ /content-type missing in HTTP POST/, /QNetworkReplyImplPrivate::error/ ] def self.write(message) puts(message) unless WARNINGS.any? { |w| message =~ w } return 0 end end Capybara.register_driver :webkit do |app| Capybara::Webkit::Driver.new(app, stderr: WarningSuppressor) end
railsrumble/r13-team-46
spec/repositories/update_task_spec.rb
<reponame>railsrumble/r13-team-46<filename>spec/repositories/update_task_spec.rb require 'unit_spec_helper' describe UpdateTask do let(:task) { stub } let(:service) { stub } let(:attributes) { stub } let(:repository) { UpdateTask.new(task) } before do task.stubs(:update_attributes).with(attributes).returns(true) end it 'parses again recurrence information' do SyncTaskRecurrence.expects(:new).with(task).returns(service) service.expects(:perform) repository.perform(attributes) end end
railsrumble/r13-team-46
app/helpers/devise_helper.rb
<reponame>railsrumble/r13-team-46 module DeviseHelper def devise_error_messages! flash[:alert] ||= [] resource.errors.full_messages.map { |msg| flash[:alert] << content_tag(:p, msg) }.join end end
railsrumble/r13-team-46
lib/tasks/handle_recurrences.rake
namespace :handle_recurrences do desc "Send mail for every passed recurrence" task perform: :environment do HandleRecurrences.perform end task daemon: :environment do while true sleep 10 HandleRecurrences.perform end end end
railsrumble/r13-team-46
db/migrate/20131019232453_add_last_at_on_recurrences.rb
class AddLastAtOnRecurrences < ActiveRecord::Migration def change add_column :recurrences, :last_at, :datetime end end
railsrumble/r13-team-46
spec/repositories/create_task_spec.rb
<reponame>railsrumble/r13-team-46<gh_stars>0 require 'unit_spec_helper' describe CreateTask do let(:repository) { CreateTask.new } let(:attributes) { stub } let(:task) { stub(persisted?: true) } before do repository.stubs(:after_create_hooks).returns([]) end it 'should delegate creation' do Task.expects(:create).with(attributes).returns(task) repository.create(attributes) end end
railsrumble/r13-team-46
db/migrate/20131019085947_rename_recurrence_fields.rb
<reponame>railsrumble/r13-team-46 class RenameRecurrenceFields < ActiveRecord::Migration def change rename_column :recurrences, :next, :next_at rename_column :recurrences, :starting, :starting_at rename_column :recurrences, :until, :until_at end end
railsrumble/r13-team-46
app/concerns/active_record_helpers.rb
module ActiveRecordHelpers def self.included(base) base.extend ClassMethods end module ClassMethods def find_for_oauth(auth) record = where(provider: auth.provider, uid: auth.uid.to_s).first record || ( if existing_user = where(email: auth.info.email).first existing_user.tap { |u| u.update_attributes(provider: auth.provider, uid: auth.uid) } else create(provider: auth.provider, uid: auth.uid, email: auth.info.email, password: <PASSWORD>.friendly_token[0,20]) end ) end end end
railsrumble/r13-team-46
spec/support/factory_girl.rb
module FactoryGirlHelpers def build_attributes_for(*args) obj = FactoryGirl.build(*args) obj.attributes.each_with_object({}) do |(key, _), result| sym = key.to_sym result[sym] = obj.send(sym) end end end RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.include FactoryGirlHelpers end
railsrumble/r13-team-46
spec/models/recurrence_spec.rb
require 'spec_helper' describe Recurrence do end
railsrumble/r13-team-46
app/services/sync_task_recurrence.rb
class SyncTaskRecurrence < Struct.new(:task) def user task.user end def perform if result = Tickle.parse(task.time_expression) result = OpenStruct.new(result) Recurrence.sync_with_task(task.id, { expression: result.expression, starting_at: moment_with_timezone(result.starting), next_at: moment_with_timezone(result.next), until_at: moment_with_timezone(result.until) }) else task.destroy task.errors.add :time_expression, I18n.t('activerecord.errors.models.task.attributes.time_expression.parse_failed') end end def moment_with_timezone(moment) TimeZoneConverter.convert(moment, user) end end
railsrumble/r13-team-46
spec/mailers/recurrence_mailer_spec.rb
require "spec_helper" describe RecurrenceMailer do end
railsrumble/r13-team-46
spec/support/rspec_config.rb
<gh_stars>0 require 'bourne' RSpec.configure do |config| config.expect_with :rspec do |c| c.syntax = :expect end config.mock_with :mocha config.order = "random" if defined?(Rails) config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = false config.infer_base_class_for_anonymous_controllers = false config.include Devise::TestHelpers, :type => :controller end end
railsrumble/r13-team-46
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. ActiveRecord::SessionStore::Session.attr_accessible :data, :session_id Evry::Application.config.session_store :active_record_store
railsrumble/r13-team-46
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_filter :save_user_time_zone, if: :current_user around_filter :set_user_time_zone, if: :current_user rescue_from CanCan::AccessDenied do |exception| flash[:alert] = "You are not allowed to see that" redirect_to root_url end def save_user_time_zone if cookies["user_time_zone"].present? && current_user.time_zone.blank? current_user.update_attribute(:time_zone, cookies["user_time_zone"]) end end def set_user_time_zone(&block) Time.use_zone(current_user.time_zone || 'UTC', &block) end end
railsrumble/r13-team-46
app/models/recurrence.rb
<filename>app/models/recurrence.rb class Recurrence < ActiveRecord::Base belongs_to :task attr_accessible :task_id, :expression, :starting_at, :next_at, :until_at, :last_at delegate :user, to: :task scope :ready, -> { where('recurrences.next_at <= ?', Time.now) } def self.sync_with_task(task_id, attributes) Recurrence.where(task_id: task_id).first_or_create.tap do |r| r.update_attributes(attributes) end end end
railsrumble/r13-team-46
app/services/time_zone_converter.rb
class TimeZoneConverter def self.convert(moment, user) offset = Time.use_zone(user.time_zone) do Time.zone.now.utc_offset end moment.advance(seconds: -1 * offset) if moment end end
railsrumble/r13-team-46
app/helpers/application_helper.rb
module ApplicationHelper def ui_button(title, link, button_options, options = {}) link_to title, link, options.merge(class: "ui #{button_options} button") end def ui_icon_button(title, css_class, link, button_options, options = {}) link_to link, options.merge(class: "ui " + button_options + " button") do content_tag(:i, "", class: "icon #{css_class}") + title end end def flash_floating_class Hash.new("error").merge({ notice: "info" }) end def flash_icon_class Hash.new("warning").merge({ notice: "ok sign teal" }) end def flash_header_message Hash.new("Whoops, something went wrong!").merge({ notice: "Success!" }) end def vertical_menu_icon_link(title, icon, url, options = {}) link_to url, options.merge(class: 'item') do content_tag(:i, "", class: "icon #{icon}") + title end end def vertical_menu_delete_icon_link(url, options = {}) link_to url, options.merge(method: :delete, class: 'item delete_button') do content_tag(:i, "", class: "icon remove") + "Delete" end end def ui_icon_only_link(icon, url, options = {}) link_to url, options do content_tag(:i, "", class: "icon #{icon}") end end def human_date(date) date.strftime('%d %B %Y, %H:%M') end def vertical_menu_icon_link(title, icon, url, options = {}) link_to url, options.merge(class: 'item') do content_tag(:i, "", class: "icon #{icon}") + title end end def ui_icon_only_link(icon, url, options = {}) link_to url, options do content_tag(:i, "", class: "icon #{icon}") end end end
railsrumble/r13-team-46
spec/factories/users.rb
<filename>spec/factories/users.rb FactoryGirl.define do factory :user do sequence(:email) { |n| "<EMAIL>" } password '<PASSWORD>' time_zone 'Europe/Rome' end end
railsrumble/r13-team-46
config/routes.rb
<reponame>railsrumble/r13-team-46<gh_stars>0 Evry::Application.routes.draw do root to: "static#welcome" get '/static/welcome' => 'static#welcome' get '/static/logged' => 'static#logged' get '/static/new' => 'static#new' get '/static/list' => 'static#list' get '/static/edit' => 'static#edit' devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" } resources :tasks, except: :edit do collection do get :mail_report end member do get :duplicate get :mail_notification get :schedule end end end
railsrumble/r13-team-46
spec/services/handle_recurrences_spec.rb
require 'unit_spec_helper' describe HandleRecurrences do let(:service) { HandleRecurrences.new } context "#recurrences" do it 'fetches all recurrences' do Recurrence.expects(:ready) service.recurrences end end context "#perform" do before do service.stubs(:recurrences).returns(recurrences) end let(:first) { stub } let(:second) { stub } let(:recurrences) do [ first, second ] end it 'should handle each recurrence' do service.expects(:handle_recurrence).with(first) service.expects(:handle_recurrence).with(second) service.perform end context "#send_mail_notification" do let(:mail) { stub } let(:recurrence) { stub(user: "alice", task: "cooking") } it 'sends an email to every recurrence' do RecurrenceMailer.expects(:notify).with("alice", "cooking").returns(mail) mail.expects(:deliver) service.send_mail_notification(recurrence) end end context "#set_last_at" do let(:recurrence) { stub(next_at: 'paperino') } it 'set last_at to next_at' do recurrence.expects(:update_attributes).with(last_at: recurrence.next_at) service.set_last_at(recurrence) end end context "#reset_next_at" do let(:recurrence) { stub } it 'resets next_at to nil' do recurrence.expects(:update_attributes).with(next_at: nil) service.reset_next_at(recurrence) end end end end
railsrumble/r13-team-46
spec/support/timecop.rb
module TimecopHelperMethods def back_to_future(options) now = Time.now Timecop.travel(now.advance(options)) end end RSpec.configuration.include TimecopHelperMethods, type: :feature
railsrumble/r13-team-46
spec/services/sync_task_recurrence_spec.rb
require 'unit_spec_helper' describe SyncTaskRecurrence do context "add recurrence" do let(:task) { stub(id: 666, user: user, time_expression: 'time expression', errors: errors) } let(:user) { stub(time_zone: 'Europe/Rome') } let(:errors) { stub } let(:result) { stub_everything } let(:service) { SyncTaskRecurrence.new(task) } before do Recurrence.stubs(:sync_with_task) end it 'should parse the time expression using pickle' do Tickle.expects(:parse).with('time expression').returns(result) service.perform end it 'should add an error if Tickle fails to parse and destroy task' do Tickle.stubs(:parse).returns(nil) task.expects(:destroy) errors.expects(:add).with(:time_expression, I18n.t('activerecord.errors.models.task.attributes.time_expression.parse_failed')) service.perform end context "recurrence creation" do let(:moment) { Time.parse("2013-10-20 13:13:25") } let(:result) do { expression: "day", starting: moment, next: moment, until: moment } end before do Tickle.stubs(:parse).returns(result) end let(:moment_with_timezone) { stub } it 'should create the recurrence object' do TimeZoneConverter.expects(:convert).with(moment, task.user).returns(moment_with_timezone).at_least(3) Recurrence.expects(:sync_with_task).with(666, { expression: "day", starting_at: moment_with_timezone, next_at: moment_with_timezone, until_at: moment_with_timezone }) service.perform end end end end
railsrumble/r13-team-46
app/controllers/static_controller.rb
class StaticController < ApplicationController def welcome if user_signed_in? redirect_to tasks_url else render 'welcome', layout: 'homepage' end end def logged end def new end def list end def edit end end