text
stringlengths
10
2.61M
require "bundler" begin Bundler.setup Bundler::GemHelper.install_tasks rescue raise "You need to install a bundle first. Try 'thor version:use 3.2.13'" end require 'yaml' require 'rspec' require 'rspec/core/rake_task' require 'cucumber/rake/task' desc "Run all examples" RSpec::Core::RakeTask.new(:spec) do |t| t.ruby_opts = %w[-w] t.rspec_opts = %w[--color] end Cucumber::Rake::Task.new(:cucumber) if RUBY_VERSION.to_f == 1.8 namespace :rcov do task :clean do rm_rf 'coverage.data' end desc "Run cucumber features using rcov" Cucumber::Rake::Task.new :cucumber do |t| t.cucumber_opts = %w{--format progress} t.rcov = true t.rcov_opts = %[-Ilib -Ispec --exclude "gems/*,features"] t.rcov_opts << %[--text-report --sort coverage --aggregate coverage.data] end desc "Run all examples using rcov" RSpec::Core::RakeTask.new :spec do |t| t.rcov = true t.rcov_opts = %[-Ilib -Ispec --exclude "gems/*,features"] t.rcov_opts << %[--text-report --sort coverage --no-html --aggregate coverage.data] end end task :rcov => ["rcov:clean", "rcov:spec", "rcov:cucumber"] end namespace :generate do desc "generate a fresh app with rspec installed" task :sample do |t| unless File.directory?('./tmp/sample') bindir = File.expand_path("bin") Dir.mkdir('tmp') unless File.directory?('tmp') sh "cp -r ./templates/sample ./tmp/sample" if test ?d, bindir Dir.chdir("./tmp/sample") do Dir.mkdir("bin") unless File.directory?("bin") sh "ln -sf #{bindir}/rake bin/rake" sh "ln -sf #{bindir}/rspec bin/rspec" sh "ln -sf #{bindir}/cucumber bin/cucumber" end end end end end def in_sample(command) Dir.chdir("./tmp/sample/") do Bundler.with_clean_env do sh command end end end namespace :db do task :migrate do in_sample "bin/rake db:migrate" end namespace :test do task :prepare do in_sample "bin/rake db:test:prepare" end end end desc 'clobber generated files' task :clobber do rm_rf "pkg" rm_rf "tmp" rm_rf "doc" rm_rf ".yardoc" end namespace :clobber do desc "clobber the generated app" task :app do rm_rf "tmp/sample" end end desc "Push docs/cukes to relishapp using the relish-client-gem" task :relish, :version do |t, args| raise "rake relish[VERSION]" unless args[:version] sh "cp Changelog.md features/" if `relish versions rspec/rspec-activemodel-mocks`.split.map(&:strip).include? args[:version] puts "Version #{args[:version]} already exists" else sh "relish versions:add rspec/rspec-activemodel-mocks:#{args[:version]}" end sh "relish push rspec/rspec-activemodel-mocks:#{args[:version]}" sh "rm features/Changelog.md" end task :default => [:spec, "clobber:app", "generate:sample", :cucumber] task :verify_private_key_present do private_key = File.expand_path('~/.gem/rspec-gem-private_key.pem') unless File.exists?(private_key) raise "Your private key is not present. This gem should not be built without that." end end task :build => :verify_private_key_present
# frozen_string_literal: true require "rails_helper" module ThinkFeelDoDashboard module SocialNetworking RSpec.describe ProfileQuestionsController, type: :controller do routes { Engine.routes } describe "GET edit" do context "for authenticated users" do let(:group) { instance_double(Group) } let(:user) { instance_double(User, admin?: true) } before do sign_in_user user end describe "when ProfileQuestion is found" do before do expect(::SocialNetworking::ProfileQuestion) .to receive(:find) do double("ProfileQuestion") end end describe "when Group is found" do before do expect(Group).to receive(:find) { group } end it "should respond with a redirect to the moderator's profile page" do get :edit, group_id: 1, id: 1 expect(response.status).to eq 200 end end describe "when Group is not found" do it "should respond with a redirect" do get :edit, group_id: 1, id: 1 expect(response.status).to eq 302 end end end describe "when ProfileQuestion is not found" do it "should respond with a redirect" do get :edit, group_id: 1, id: 1 expect(response.status).to eq 302 end end end context "for unauthenticated users" do before { get :edit, group_id: 1, id: 1 } it_behaves_like "a rejected user action" end end end end end
module StormFury class Server attr_reader :attributes, :options attr_accessor :service def self.create(attributes, options = {}) server = new(attributes, options) server.create end def initialize(attributes, options = {}) @attributes = attributes @options = options self.service = options.fetch(:service, StormFury.default_service) end def create Resource::Server.create(attributes, { service: service }) end end end
class TracksController < ApplicationController # GET /tracks # GET /tracks.json def index @tracks = Track.joins(:ratings).includes(:ratings).order('tracks.updated_at desc') @recent = Lastfm.recent end # GET /tracks/1 # GET /tracks/1.json def show if params[:artist].present? @api = Lastfm.find CGI::unescape(params[:artist]), CGI::unescape(params[:track]) artist = @api['track']['artist']['name'] track_name = @api['track']['name'] image = @api['track']['album']['image'][1]['#text'] if @api['track']['album'].present? @track = Track.find_or_create_by_artist_and_track :artist => artist, :track => track_name, :image => image else @track = Track.find params[:id] @api = Lastfm.find @track.artist, @track.track end respond_to do |format| format.html # show.html.erb format.json { render :json => @track } end end # GET /tracks/new # GET /tracks/new.json def new @track = Track.new respond_to do |format| format.html # new.html.erb format.json { render :json => @track } end end # GET /tracks/1/edit def edit @track = Track.find(params[:id]) end # POST /tracks # POST /tracks.json def create @track = Track.new(params[:track]) respond_to do |format| if @track.save format.html { redirect_to @track, :notice => 'Track was successfully created.' } format.json { render :json => @track, :status => :created, :location => @track } else format.html { render :action => "new" } format.json { render :json => @track.errors, :status => :unprocessable_entity } end end end # PUT /tracks/1 # PUT /tracks/1.json def update @track = Track.find(params[:id]) respond_to do |format| if @track.update_attributes(params[:track]) format.html { redirect_to @track, :notice => 'Track was successfully updated.' } format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @track.errors, :status => :unprocessable_entity } end end end # DELETE /tracks/1 # DELETE /tracks/1.json def destroy @track = Track.find(params[:id]) @track.destroy respond_to do |format| format.html { redirect_to tracks_url } format.json { head :no_content } end end end
module Kilomeasure # Loads a measure definition and the formulas associated with it. # class MeasureLoader < ObjectBase fattrs :data_path attr_reader :data, :measure def initialize(*) super self.data_path ||= DATA_PATH end def each_measure_from_file Dir["#{data_path}/measures/*.yml"].each do |file_name| yield load_from_file(File.basename(file_name, '.yml')) end end def load_from_data(name, data) formulas = FormulasCollection.new(build_formulas(data)) output_formulas = FormulasCollection.new(build_output_formulas(data)) field_definitions = data.fetch(:field_definitions, {}) lookups = data.fetch(:lookups, {}) inputs_only = data.fetch(:inputs_only, false) inputs = build_inputs(data) defaults = data.fetch(:defaults, {}) data_types = data.fetch(:data_types, []) options = { field_definitions: field_definitions, name: name, formulas: formulas, output_formulas: output_formulas, defaults: defaults, lookups: lookups, inputs: inputs, inputs_only: inputs_only, data_types: data_types } Measure.new(options) end def load_from_file(name) @data = measure_file_contents(name) load_from_data(name, data) end private def build_formulas(data) data_types = data.fetch(:data_types, []) default_formulas = DEFAULT_FORMULAS.select do |formula_name, _formula| if formula_name =~ DATA_TYPES_REGEXP data_type = DATA_TYPES_REGEXP.match(formula_name)[1] next false unless data_types.include?(data_type.to_s) end true end formulas = default_formulas.merge( data.fetch(:formulas, {})) formulas.map do |name, formula| Formula.new(name: name, expression: formula) end + formulas_from_lookups(data) end def build_inputs(data) field_names = data.fetch(:inputs, []) field_names.map do |field_name| Input.new(name: field_name) end end def build_output_formulas(data) data_types = data.fetch(:data_types, []) default_output_formulas = DEFAULT_OUTPUT_FORMULAS.select do |formula_name, _formula| if formula_name =~ DATA_TYPES_REGEXP data_type = DATA_TYPES_REGEXP.match(formula_name)[1] next false unless data_types.include?(data_type.to_s) end true end formulas = default_output_formulas.merge( data.fetch(:output_formulas, {}) ) formulas.map do |name, expression| Formula.new(name: name, expression: expression) end end def expression_proc lambda do |input_name, pairs| key, value = pairs.shift if key next_condition = expression_proc.call(input_name, pairs) else return "'finally'" end <<-EXPRESSION.strip_heredoc IF(#{input_name} = #{key.is_a?(Numeric) ? key : "'#{key}'"}, #{value}, #{next_condition}) EXPRESSION end end def formulas_from_lookups(data) data.fetch(:lookups, {}).map do |name, options| lookup = options.fetch(:lookup).with_indifferent_access input_name = options.fetch(:input_name).to_sym pairs = lookup.to_a expression = expression_proc.call(input_name, pairs) Formula.new( expression: expression, name: name, additional_dependencies: [input_name]) end end private def measure_file_contents(name) measure_file = File.join(data_path, 'measures', "#{name}.yml") YAML.load_file(measure_file).deep_symbolize_keys rescue Errno::ENOENT {} end end end
class HomeController < ApplicationController before_action :basic_http_auth def index @pictures = Picture.order(:created_at) if params[:query] @pictures = @pictures.where("title ilike ? OR description ilike ?", "%#{params[:query]}%", "%#{params[:query]}%") end end private def basic_http_auth return if Rails.env == 'development' authenticate_or_request_with_http_basic do |username, password| username == ENV['PUBLIC_USERNAME'] && password == ENV['PUBLIC_PASSWORD'] end end end
class Review < ApplicationRecord validates :body, :user_id, :restaurant_id, null: false belongs_to :user belongs_to :restaurant end
require_relative '../support/helpers/helper' RSpec.describe PagseguroRecorrencia do before(:each) do new_configuration end context 'when call get_card_brand() method' do it 'when pass a correct bin' do bin = '411111' response = PagseguroRecorrencia.get_card_brand(bin) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:body].key?(:bin)).to be_truthy expect(response[:body][:bin].key?(:bin)).to be_truthy expect(response[:body][:bin].key?(:brand)).to be_truthy expect(response[:body][:bin][:bin]).to eq(411111) expect(response[:body][:bin][:brand][:name]).to eq('visa') expect(response[:body][:bin][:status_message]).to eq('Success') end it 'when pass a incorrect bin' do bin = '454545' response = PagseguroRecorrencia.get_card_brand(bin) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:body][:status_message]).to eq('Error') expect(response[:body][:reason_message]).to eq('Bin not found') end it 'when request return 404 not found' do bin = '404' response = PagseguroRecorrencia.get_card_brand(bin) expect(response.class).to eq(Hash) expect(response.key?(:code)).to be_truthy expect(response.key?(:message)).to be_truthy expect(response.key?(:body)).to be_truthy expect(response[:code]).to eq('404') expect(response[:message]).to eq('Not Found') expect(response[:body]).to be_nil end end end
class IHGRewardsWebsite include PageObject include DataMagic page_url FigNewton.ihg_rewards_website a(:ihg_logo, :id => 'idHeaderLogo') def wait_for_ihg_website wait_until do ihg_logo_element.visible? end end end
module GapIntelligence # @see https://api.gapintelligence.com/api/doc/v1/advertisements.html module Advertisements # Requests a list of advertisements # # @param params [Hash] parameters of the http request # @param options [Hash] the options to make the request with # @yield [req] The Faraday request # @return [RecordSet<Advertisement>] the requested merchants # @see https://api.gapintelligence.com/api/doc/v1/advertisements/index.html def advertisements(params = {}, options = {}, &block) default_option(options, :record_class, Advertisement) perform_request(:get, 'advertisements', options.merge(params: params), &block) end end end
class ChangeDataTypeForGcacheResult < ActiveRecord::Migration def up change_table :gcaches do |t| t.change :result, :text end end def down change_table :gcaches do |t| t.change :result, :string end end end
require './models/book' require './serializers/book_serializer' get '/ ' do 'Welcome to BookList!' end namespace '/api/v1' do efore do content_type 'application/json' end helpers do def base_url @base_url ||= "#{request.env['rack.url_scheme']}://{request.env['HTTP_HOST']}" end def json_params begin JSON.parse(request.body.read) rescue halt 400, { message:'Invalid JSON' }.to_json end end def book @book ||= Book.where(id: params[:id]).first end def halt_if_not_found! halt(404, { message:'Book Not Found'}.to_json) unless book end def serialize(book) BookSerializer.new(book).to_json end end get '/books' do books = Book.all [:title, :isbn, :author].each do |filter| books = books.send(filter, params[filter]) if params[filter] end books.map { |book| BookSerializer.new(book) }.to_json end get '/books' do books = Book.all [:title, :isbn, :author].each do |filter| books = books.send(filter, params[filter]) if params[filter] end books.map { |book| BookSerializer.new(book) }.to_json end get '/books/:id' do |id| halt_if_not_found! serialize(book) end post '/books ' do book = Book.new(json_params) halt 422, serialize(book) unless book.save response.headers['Location'] = "#{base_url}/api/v1/books/#{book.id}" status 201 end patch '/books/:id' do |id| halt_if_not_found! halt 422, serialize(book) unless book.update_attributes(json_params) serialize(book) end delete '/books/:id' do |id| book.destroy if book status 204 end end
FactoryGirl.define do factory :guest do email 'guest@forecast.com' password 'password' first_name 'Guest' last_name 'Forecast' image 'image-url' sex 'Male' birthday '2015-01-30' username 'username' end end
class RemoveCommunityFromParticipants < ActiveRecord::Migration def up remove_column :participants, :community end def down add_column :participants, :community, :string end end
require 'rails_helper' RSpec.describe Api::V1::UsersController, type: :controller do let(:user) { create(:user) } describe 'PATCH /user' do context 'successful update' do it "reponds with suceess" do api_user user patch :update, {} expect(response).to be_success end it "returns user data" do api_user user patch :update, {} expect(response.body).to serialize_object(user) .with(UserSerializer, :include => ['organization', 'badges']) end it "updates user's information" do organization = create(:organization) api_user user patch :update, { organization_id: organization.id } expect(json['data']['relationships']['organization']['data']['id']).to eq(organization.id.to_s) end end end describe 'GET /user' do context 'with a successful call' do it "reponds with suceess" do api_user user get :show expect(response).to be_success end it "returns user's session data" do api_user user get :show expect(json).to have_key('data') expect(json['data']['type']).to eq('givdoTokenAuthSessions') end end end end
require 'open-uri' require 'nokogiri' module LeagueGrabber::GetTable def get_league_table # Get me Premier League Table url = 'http://www.bbc.co.uk/sport/football/tables' doc = Nokogiri::HTML.parse(open url) teams = doc.search('tbody tr.team') keys = teams.first.search('td').map do |k| k['class'].gsub('-', '_').to_sym end hsh = teams.flat_map do |team| Hash[keys.zip(team.search('td').map(&:text))] end hsh.map do |k| position = k[:position].gsub(/[Nomovement ]/, "") team_name = k[:team_name] points = k[:points] goal_difference = k[:goal_difference] played = k[:played] League.create!(position: position, team_name: team_name, points: points, goal_difference: goal_difference, played: played) end end end
require('minitest/autorun') require('minitest/rg') require_relative('../fish.rb') require_relative('../river.rb') require_relative('../bears.rb') class BearsTest < MiniTest::Test def setup() @bears = Bears.new("Beatrice", "Grizzly") @fish1 = Fish.new("salmon") @fish2 = Fish.new("sturgeon") @fish3 = Fish.new("trout") #@fish = River.new("Yukon River", @fish) end def test_bear_name() assert_equal("Beatrice", @bears.name()) end def test_bear_type() assert_equal("Grizzly", @bears.type) end def test_catch_fish_from_river() @bears.bear_catch_fish(@fish1) assert_equal(1, @bears.fish_eaten()) end def test_bear_empty_stomach() @bears.bear_catch_fish(@fish1) @bears.bear_catch_fish(@fish2) @bears.empty_stomach() assert_equal(0, @bears.fish_eaten()) end def test_river_lose_fish() @fish_population = River.new("Yukon River", @fish) @fish_population.river_lose_fish(@fish1) assert_equal(2, @bears.river_population()) # @bears.river_lose_fish(@fish1) # assert_equal(2, @bears.river_population()) end def test_bear_roar() assert_equal("Raaaaaaawr!", @bears.bear_roar()) end end
class CharactersCreateConversations < ActiveRecord::Migration def change create_table :conversations do |t| t.string :code, null:false t.boolean :initial, default:false t.boolean :repeatable, default:false t.text :results end add_index :conversations, :code, unique:true end end
require 'rails_helper' RSpec.describe Note, type: :model do it { should belong_to(:user) } it { should have_many(:taggings) } it { should have_many(:tags).through(:taggings) } context "callback methods" do before(:each) do @user = User.create( email: 'foobar@foobar.com', password: 'foobar', password_confirmation: 'foobar' ) end describe "#create_tags" do it "creates new tags when a note is created with new tags" do @user.notes.create( title: '#hashtag1 @mention1 foobar', body: '#hashtag2 @mention2 foobar', ) expect(Tag.find_by(name: 'hashtag1', mention: false)).to be expect(Tag.find_by(name: 'hashtag2', mention: false)).to be expect(Tag.find_by(name: 'mention1', mention: true)).to be expect(Tag.find_by(name: 'mention2', mention: true)).to be end it "creates new associations when a note is created with existing tags" do note1 = @user.notes.create( title: '#hashtag1 @mention1 foobar', body: '#hashtag2 @mention2 foobar' ) note2 = @user.notes.create( title: '#hashtag1 @mention1 foobaz', body: '#hashtag2 @mention2 foobaz' ) expect(Tag.all.count).to eq(4) expect(note2.tags.find_by(name: 'hashtag1', mention: false)).to be expect(note2.tags.find_by(name: 'hashtag2', mention: false)).to be expect(note2.tags.find_by(name: 'mention1', mention: true)).to be expect(note2.tags.find_by(name: 'mention2', mention: true)).to be end it "won't create duplicate taggings when updating notes" do note = @user.notes.create(title: '#hashtag') note.update!(title: note.title += ' foo') expect(Tagging.all.count).to eq(1) end end end end
class AddImageToRetails < ActiveRecord::Migration[5.2] def change add_column :retails, :retail_image, :string end end
RSpec.describe Kalculator::Formula do describe "contains" do context "with strings" do it "returns true when there is a match" do expect(Kalculator.evaluate("contains(\"ohai\", \"oh\")")).to eq(true) end it "returns false when there is no match" do expect(Kalculator.evaluate("contains(\"ohai\", \"Dwight\")")).to eq(false) end end context "with lists" do it "can find an integer in a list of integers" do expect(Kalculator.evaluate("contains([1,2,3], 2)")).to eq(true) expect(Kalculator.evaluate("contains([1,2,3], 4)")).to eq(false) end end it "handles incorrect types on string" do data = Kalculator::TypeSources.new({"a" => Kalculator::Number, "b" => Kalculator::String.new}) begin Kalculator.validate("contains(a, b)", data) rescue Kalculator::Error => e expect(e.class).to be <= (Kalculator::TypeError) end end it "handles incorrect types on substring" do data = Kalculator::TypeSources.new({"a" => Kalculator::String.new, "b" => Kalculator::Number}) begin Kalculator.validate("contains(a, b)", data) rescue Kalculator::Error => e expect(e.class).to be <= (Kalculator::TypeError) end end end describe "count" do it "can count the entries in a list" do expect(Kalculator.evaluate("count(numbers)", {"numbers" => [1,2,3,4]})).to eq(4) end it "can count the entries in a list literal" do expect(Kalculator.evaluate("count([true, false, true, false, true, false])")).to eq(6) end it "cannot count numbers" do expect { Kalculator.validate("count(6)") }.to raise_error(Kalculator::TypeError) end it "cannot count strings" do expect { Kalculator.validate("count(\"ohai\")") }.to raise_error(Kalculator::TypeError) end end describe "sum" do it "can sum a list of numbers" do expect(Kalculator.evaluate("sum(numbers)", {"numbers" => [1,2,3,4]})).to eq(10) end it "can sum floating point numbers" do sum = Kalculator.evaluate("sum(numbers)", {"numbers" => [2,3.5]}) expect(sum).to be_within(0.01).of(5.5) end it "can sum over an list literal" do sum = Kalculator.evaluate("sum([1, 2, 3, 4, 5])") expect(sum).to equal(15) end it "handles incorrect container type" do expect { Kalculator.validate("sum(\"wat\")") }.to raise_error(Kalculator::TypeError) end it "handles incorrect array contents" do expect { Kalculator.validate("sum(numbers)", Kalculator::TypeSources.new({"numbers" => Kalculator::List.new(Object)})) }.to raise_error(Kalculator::TypeError) end end describe "max" do it "returns the max of two numbers" do expect(Kalculator.evaluate("max(18, 20)")).to eq(20) expect(Kalculator.evaluate("max(20, 18)")).to eq(20) expect(Kalculator.evaluate("max(100.0, 20)")).to eq(100.0) end it "handles incorrect types" do expect { Kalculator.validate("max(\"ohai\", 5)") }.to raise_error(Kalculator::TypeError) expect { Kalculator.validate("max(4, [1, 2, 3])") }.to raise_error(Kalculator::TypeError) end end describe "min" do it "returns the min of two numbers" do expect(Kalculator.evaluate("min(18, 20)")).to eq(18) expect(Kalculator.evaluate("min(20, 18)")).to eq(18) expect(Kalculator.evaluate("min(1.0, 20)")).to eq(1.0) end it "handles incorrect types" do expect { Kalculator.validate("min(\"ohai\", 5)") }.to raise_error(Kalculator::TypeError) expect { Kalculator.validate("min(4, [1, 2, 3])") }.to raise_error(Kalculator::TypeError) end end it "raises a specific error for undefined functions" do expect { Kalculator.evaluate("wat(123)") }.to raise_error(Kalculator::UndefinedFunctionError, "no such function wat/1") end end
class CommentsController < ApplicationController before_action :find_deck # before executing any action find the deck we are working with, # no need to specify an 'only' since we want to get the deck on each operation before_action :find_comment, only: [:edit, :update, :destroy] # same as above, but we don't need to find # a comment for the 'create' function. before_action :authenticate_user! # prevents unauthenticated user from creating a commment def create @comment = @deck.comments.create(comment_params) @comment.user_id = current_user.id if @comment.save redirect_to deck_path(@deck) else render 'new' end end def edit @comment = @deck.comments.find(params[:id]) end def update if @comment.update(comment_params) redirect_to deck_path(@deck) else render 'edit' end end def destroy @comment.destroy redirect_to deck_path(@deck) end private def comment_params params.require(:comment).permit(:content) # grabs comment object from parameters, then sends end # back a copy of the content inside permit def find_deck @deck = Deck.find(params[:deck_id]) end def find_comment @comment = @deck.comments.find(params[:id]) end end
class Post < ActiveRecord::Base # I am using active record to validate user input #is invalid with no title #is invalid when content is too short or too long #is invalid if its not one of the predefined categories #is invalid if not clickbait validates :title, presence: true validates :content, length: { minimum: 100 } validates :category, inclusion: { in: %w(Fiction Non-Fiction) } end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Filterable do it 'filters by params' do create_list(:repository_index, 5) result = Repository.all expect(result.filter(language: 'ruby', deployable: 'true', dependency: 'existence', monitorable: 'true', tested: 'true', documented: 'false').count).to eq 5 end end
# frozen_string_literal: true class GradeSerializerV2 < ActiveModel::Serializer attribute :lesson_uid, key: :lesson_id attributes :student_id, :deleted_at, :skill_id, :mark belongs_to :student belongs_to :lesson belongs_to :grade_descriptor end
# frozen_string_literal: true class MoveAttendanceWebPushFromMemberToUser < ActiveRecord::Migration[7.0] def change add_reference :attendance_webpushes, :user AttendanceWebpush.all.each do |awp| awp.user_id = Member.find(awp.member_id).user_id end remove_column :attendance_webpushes, :member_id, :bigint end end
require 'rails_helper' RSpec.describe 'User', type: :model do it 'is not valid without an email' do user = User.new(password: '123456') expect(user.save).to be(false) end it 'is not valid without an password' do user = User.new(email: 'p@gmail.com') expect(user.save).to be(false) end it 'is saves each field of the user' do user = User.new(email: 'p@gmail.com', password: '123456') expect(user.email).to eql('p@gmail.com') end it 'can have many events' do a = User.reflect_on_association(:articles) expect(a.macro).to eq(:has_many) end it 'can have many events' do a = User.reflect_on_association(:votes) expect(a.macro).to eq(:has_many) end end
class Blog < ApplicationRecord validates :first_name, :last_name, :phone, :email, :country, :presence => true end
# Longest String # I worked on this challenge [by myself]. # longest_string is a method that takes an array of strings as its input # and returns the longest string # # +list_of_words+ is an array of strings # longest_string(list_of_words) should return the longest string in +list_of_words+ # # If +list_of_words+ is empty the method should return nil # Your Solution Below def longest_string(list_of_words) tol = list_of_words[0] howtol = -1 list_of_words.each do |comp| if comp.length > howtol howtol = comp.length tol = comp end end return tol end
require 'binary_heap' class PriorityQueue include BinaryHeap def initialize max_heap=false @elements = [] @is_min_heap = !max_heap end def pop @elements.shift end # I need to be able to keep track of the elements # While their positions change, we still need to be able to access the actual keys # If someone gives us a bunch of numbers, that's fair. We can just use the index. # However # How can I decrease a key # In the priority queue # Priority Queue.decrease key (Object) # If Object is a primitive or a string, not helpful # We can also give them the index of an object # Priority Queue . get Index (Object) # We can have a hashmap for that object # But that assumes that we won't have duplicate objects # Only solution so far, is just to reheapifyu def <<(element) @elements << element bubble_up @elements, @elements.size - 1 end def updateKey(index, newValue) return if index >= @elements.size return if index < 0 old = @elements[index] @elements[index] = newValue # If min heap and new value is less than old, bubble up, else bubble down if (is_min_heap?) if (newValue < old) bubble_up @elements, index else bubble_down @elements, index end end # If max heap and new value is greater than old, bubble up, else bubble down if (is_max_heap?) if (newValue > old) bubble_up @elements, index else bubble_down @elements, index end end end def getMin if is_min_heap? pop else size = @elements.size last_index = size - 1 smallest = last_index if @elements[size - 2] < @elements[last_index] smallest = size - 2 end if last_index == smallest @elements.pop else last_item = @elements.pop smallest_item = @elements.pop @elements << last_item smallest_item end end end def getMax if is_max_heap? pop else size = @elements.size last_index = size - 1 largest = last_index if @elements[size - 2] > @elements[last_index] largest = size - 2 end if last_index == largest @elements.pop else last_item = @elements.pop largest_item = @elements.pop @elements << last_item largest_item end end end def empty? @elements.empty? end private attr_reader :elements, :is_min_heap def swap array, i, j array[i], array[j] = array[j], array[i] end end
require File.expand_path(File.join(File.dirname(__FILE__), '../spec_helper')) require File.expand_path(File.join(File.dirname(__FILE__), '../app')) module InterestsViaForumSpecHelper def setup_mocks @forum = mock('Forum') @forum_interests = mock('forum_interests assoc') Forum.stub!(:find).and_return(@forum) @forum.stub!(:interests).and_return(@forum_interests) @forum.stub!(:to_param).and_return('1') end end describe "Routing shortcuts for Interests via Forum (forums/1/interests/2) should map" do include InterestsViaForumSpecHelper controller_name :interests before(:each) do setup_mocks @interest = mock('Interest') @interest.stub!(:to_param).and_return('2') @forum_interests.stub!(:find).and_return(@interest) get :show, :forum_id => "1", :id => "2" end it "resources_path to /forums/1/interests" do controller.resources_path.should == '/forums/1/interests' end it "resource_path to /forums/1/interests/2" do controller.resource_path.should == '/forums/1/interests/2' end it "resource_path(9) to /forums/1/interests/9" do controller.resource_path(9).should == '/forums/1/interests/9' end it "edit_resource_path to /forums/1/interests/2/edit" do controller.edit_resource_path.should == '/forums/1/interests/2/edit' end it "edit_resource_path(9) to /forums/1/interests/9/edit" do controller.edit_resource_path(9).should == '/forums/1/interests/9/edit' end it "new_resource_path to /forums/1/interests/new" do controller.new_resource_path.should == '/forums/1/interests/new' end end describe "Requesting /forums/1/interests using GET" do include InterestsViaForumSpecHelper controller_name :interests before(:each) do setup_mocks @interests = mock('Interests') @forum_interests.stub!(:find).and_return(@interests) end def do_get get :index, :forum_id => 1 end it "should find the forum" do Forum.should_receive(:find).with('1').and_return(@forum) do_get end it "should assign the found forum as :interested_in for the view" do do_get assigns[:interested_in].should == @forum end it "should assign the forum_interests association as the interests resource_service" do @forum.should_receive(:interests).and_return(@forum_interests) do_get @controller.resource_service.should == @forum_interests end end
Given (/^my HTTP basic auth credentials are incorrect$/) do @basic_auth_user = 'INCORRECT_USER_NAME' @basic_auth_password = 'INCORRECT_USER_PASSWORD' end Given (/^I use a service broker with a bad Conjur URL$/) do @service_broker_host = 'http://service-broker-bad-url:3001' end Given (/^I use a service broker with a bad Conjur API key$/) do @service_broker_host = 'http://service-broker-bad-key:3002' end Given (/^I use a service broker with a non-root policy$/) do @service_broker_host = 'http://service-broker-alt-policy:3003' end Given (/^I use a service broker with an improperly privileged host$/) do @service_broker_host = 'http://service-broker-bad-host:3004' end Given (/^I use a service broker with the follower URL environment variable set$/) do @service_broker_host = 'http://service-broker-follower-url:3005' end Given (/^my request doesn't include the X-Broker-API-Version header$/) do headers.reject! { |k, _| ['X-Broker-API-Version'].include? k } end When(/^I make a bind request with an existing binding_id and body:$/) do |body| url = "/v2/service_instances/#{SecureRandom.uuid}/service_bindings/#{SecureRandom.uuid}" step "I PUT \"#{url}\" with body:", body step "I PUT \"#{url}\" with body:", body end When(/^I make a bind request with body:$/) do |body| @service_id = SecureRandom.uuid @binding_id = SecureRandom.uuid url = "/v2/service_instances/#{@service_id}/service_bindings/#{@binding_id}" step "I PUT \"#{url}\" with body:", body end When(/^I make a corresponding unbind request$/) do url = "/v2/service_instances/#{@service_id}/service_bindings/#{@binding_id}?service_id=service-id-here&plan_id=plan-id-here" step "I DELETE \"#{url}\"" end When(/^I GET "([^"]*)"$/) do |path| try_request do get_json path, { user: @basic_auth_user, password: @basic_auth_password, host: @service_broker_host } end end When(/^I PUT "([^"]*)" with body:$/) do |path, body| try_request do put_json path, body, { user: @basic_auth_user, password: @basic_auth_password, host: @service_broker_host } end end When(/^I PATCH "([^"]*)" with body:$/) do |path, body| try_request do patch_json path, body, { user: @basic_auth_user, password: @basic_auth_password, host: @service_broker_host } end end When(/^I DELETE "([^"]*)"$/) do |path| try_request do delete_json path, { user: @basic_auth_user, password: @basic_auth_password, host: @service_broker_host } end end
# 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) Compliment.destroy_all Compliment.create([ { title:'1', description:'You are awesome' }, { title:'2', description:'You are a ray of sunshine' }, { title:'3', description:'Without you my sun does not shine' }, { title:'4', description:'You are the air that I breathe to survive' }, { title:'5', description:'My Happiest moments would be incomplete if you are not by my side' }, { title:'6', description:'I value my breath, it would be nice if you didn not take it away every time you walk by' }, { title:'7', description:'Your smile is contagious' }, { title:'8', description:'Your smile brightens up the room' }, { title:'9', description:'There is no one like you' }, { title:'10', description:'You are incredible' }, { title:'11', description:'If you are next to me, there is no darkness I cannot overcome' }, { title:'12', description:'You are my connection to the sun' }, { title:'13', description:'Guess what I am wearing? The smile that you gave me today' }, { title:'14', description:'Somebody call the cops, because it is got to be illegal to look that good!' }, { title:'15', description:'Life without you is like a broken pencil... pointless' }, { title:'16', description:'Are you French because Eiffel for you' }, { title:'17', description:'I was blinded by your beauty, now let me go to the eye doctor' }, { title:'18', description:'I must be in a museum, because you truly are a work of art' }, { title:'19', description:'I must be a snowflake, because I have fallen for you' }, { title:'20', description:'Thank god I am wearing gloves because you are too hot to handle' }, { title:'21', description:'Was your father a thief? ‘Cause someone stole the stars from the sky and put them in your eyes.' }, { title:'22', description:'Are you a parking ticket? Cause you’ve got fine written all over you' }, { title:'23', description:'Aside from being sexy, what do you do for a living?' }, { title:'24', description:'Was your dad a boxer? Because damn, you’re a knockout' }, { title:'25', description:'Are you a magician? Because whenever I look at you, everyone else disappears' }, { title:'26', description:'So last night, I was reading a book about numbers and I realize that I do not have yours' }, { title:'27', description:'If a fat man puts you in a bag at night, don not worry I told Santa I wanted you for Christmas.' }, { title:'28', description:'Hi, how was heaven when you left it?' }, { title:'29', description:'You look good today! All that working out is working out' }, { title:'30', description:'If a fat man puts you in a bag at night, don not worry I told Santa I wanted you for Christmas.' } ])
require "./lib/etiqueta.rb" class Menu def initialize(nombre, &block) @nombre = nombre @desayunos = [] @almuerzos = [] @cenas = [] if block_given? if block.arity == 1 yield self else instance_eval(&block) end end end def titulo(name) @titulo = name end def ingesta(options = {} ) @min = (options[:min]) if options[:min] @max = (options[:max]) if options[:max] end def valor_energetico_total @valor_energetico = @desayunos.map{|x| x.valor_energetico_kcal}.reduce(:+) @valor_energetico += @almuerzos.map{|x| x.valor_energetico_kcal}.reduce(:+) @valor_energetico += @cenas.map{|x| x.valor_energetico_kcal}.reduce(:+) end def desayuno(descripcion, options = {}) grasas = options[:grasas] ? options[:grasas] : 0.0 grasas_s = options[:grasas_s] ? options[:grasas_s] : 0.0 hidratos = options[:hidratos] ? options[:hidratos] : 0.0 azucares = options[:azucares] ? options[:azucares] : 0.0 proteinas = options[:proteinas] ? options[:proteinas] : 0.0 sal = options[:sal] ? options[:sal] : 0.0 grasas_mon = options[:grasas_mon] ? options[:grasas_mon] : 0.0 grasas_pol = options[:grasas_pol] ? options[:grasas_pol] : 0.0 polialcoholes = options[:polialcoholes] ? options[:polialcoholes] : 0.0 almidon = options[:almidon] ? options[:almidon] : 0.0 fibra = options[:fibra] ? options[:fibra] : 0.0 vitaminas = options[:vitaminas] ? options[:vitaminas] : 0.0 minerales = options[:minerales] ? options[:minerales] : 0.0 etiqueta = Tag.new(grasas , grasas_s , hidratos , azucares , proteinas , sal , grasas_mon , grasas_pol , polialcoholes , almidon , fibra , vitaminas , minerales) etiqueta.valor_energetico_kcal() @desayunos << etiqueta end def almuerzo(descripcion ,options = {}) grasas = options[:grasas] ? options[:grasas] : 0.0 grasas_s = options[:grasas_s] ? options[:grasas_s] : 0.0 hidratos = options[:hidratos] ? options[:hidratos] : 0.0 azucares = options[:azucares] ? options[:azucares] : 0.0 proteinas = options[:proteinas] ? options[:proteinas] : 0.0 sal = options[:sal] ? options[:sal] : 0.0 grasas_mon = options[:grasas_mon] ? options[:grasas_mon] : 0.0 grasas_pol = options[:grasas_pol] ? options[:grasas_pol] : 0.0 polialcoholes = options[:polialcoholes] ? options[:polialcoholes] : 0.0 almidon = options[:almidon] ? options[:almidon] : 0.0 fibra = options[:fibra] ? options[:fibra] : 0.0 vitaminas = options[:vitaminas] ? options[:vitaminas] : 0.0 minerales = options[:minerales] ? options[:minerales] : 0.0 etiqueta = Tag.new(grasas , grasas_s , hidratos , azucares , proteinas , sal , grasas_mon , grasas_pol , polialcoholes , almidon , fibra , vitaminas , minerales) etiqueta.valor_energetico_kcal() @almuerzos << etiqueta end def cena(descripcion ,options = {}) grasas = options[:grasas] ? options[:grasas] : 0.0 grasas_s = options[:grasas_s] ? options[:grasas_s] : 0.0 hidratos = options[:hidratos] ? options[:hidratos] : 0.0 azucares = options[:azucares] ? options[:azucares] : 0.0 proteinas = options[:proteinas] ? options[:proteinas] : 0.0 sal = options[:sal] ? options[:sal] : 0.0 grasas_mon = options[:grasas_mon] ? options[:grasas_mon] : 0.0 grasas_pol = options[:grasas_pol] ? options[:grasas_pol] : 0.0 polialcoholes = options[:polialcoholes] ? options[:polialcoholes] : 0.0 almidon = options[:almidon] ? options[:almidon] : 0.0 fibra = options[:fibra] ? options[:fibra] : 0.0 vitaminas = options[:vitaminas] ? options[:vitaminas] : 0.0 minerales = options[:minerales] ? options[:minerales] : 0.0 etiqueta = Tag.new(grasas , grasas_s , hidratos , azucares , proteinas , sal , grasas_mon , grasas_pol , polialcoholes , almidon , fibra , vitaminas , minerales) etiqueta.valor_energetico_kcal() @cenas << etiqueta end def to_s aux = "#{' ' * 24 }" output = @nombre output << " Composición nutricional" output << "\n#{'=' * 150}\n\n" output << "#{aux}grasas\thidratos\tazucares\tproteinas\tsal\tpolialcoholes\talmidon\tfibra\tvitaminas\tminerales\tvalor energetico\n" output << "Desayuno\n" output << @desayunos.join output << "\nAlmuerzo\n" output << @almuerzos.join output << "\nCena\n" output << @cenas.join output << "\n#{'=' * 150}\n\n" output << "Valor energético total: #{valor_energetico_total}\t Ingesta mix: #{@min}\tIngesta max: #{@max}" end end
class NutritionalInfo < ApplicationRecord belongs_to :ingredient belongs_to :added_by, class_name: 'User' has_many :derived_measurements has_many :recipe_steps, as: :info_or_measurement, dependent: :destroy has_many :report_cases, as: :reported, dependent: :destroy end
require File.dirname(__FILE__) + "/../spec_helper" describe Preflight::Rules::PageBoxWidth do it "should pass files with a correctly sized MediaBox defined by Float points" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 595.276, :pts) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should pass files with a correctly sized MediaBox defined by Range points" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 595..596, :pts) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Float points" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 590, :pts) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Range points" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 590..591, :pts) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end it "should pass files with a correctly sized MediaBox defined by Float mm" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 210, :mm) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should pass files with a correctly sized MediaBox defined by Range mm" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 209..211, :mm) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Float mm" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 209, :mm) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Range mm" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 200..201, :mm) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end it "should pass files with a correctly sized MediaBox defined by Float inches" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 8.26, :in) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should pass files with a correctly sized MediaBox defined by Range inches" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 8..9, :in) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Float inches" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 9, :in) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end it "should fail files with an incorrectly sized MediaBox defined by Range inches" do filename = pdf_spec_file("pdfx-1a-subsetting") rule = Preflight::Rules::PageBoxWidth.new(:MediaBox, 10..11, :in) PDF::Reader.open(filename) do |reader| reader.page(1).walk(rule) rule.issues.should_not be_empty end end end
# -*- coding: utf-8 -*- require 'pukiwikiparser' class PukiwikiFilter < TextFilter description_file File.dirname(__FILE__) + "/../pukiwiki.html" # このメソッドで入力値を変換します。 def filter(text) pukiwiki = PukiWikiParser.new(Logger.new(STDOUT)) return pukiwiki.to_html(text, "dummypagename") text end end
feature 'testing framework' do scenario 'index page loads and capybara works' do visit('/') expect(page.status_code).to be(200) end end
class HadoopInstance < ActiveRecord::Base attr_accessible :name, :host, :port, :description, :username, :group_list belongs_to :owner, :class_name => 'User' has_many :activities, :as => :entity has_many :events, :through => :activities has_many :hdfs_entries validates_presence_of :name, :host, :port after_create :create_root_entry attr_accessor :highlighted_attributes, :search_result_notes searchable do text :name, :stored => true, :boost => SOLR_PRIMARY_FIELD_BOOST text :description, :stored => true, :boost => SOLR_SECONDARY_FIELD_BOOST string :grouping_id string :type_name string :security_type_name end def url "gphdfs://#{host}:#{port}/" end def self.full_refresh(id) find(id).refresh end def refresh(path = "/") entries = HdfsEntry.list(path, self) entries.each { |entry| refresh(entry.path) if entry.is_directory? } rescue Hdfs::DirectoryNotFoundError => e return unless path == '/' hdfs_entries.each do |hdfs_entry| hdfs_entry.mark_stale! end end def create_root_entry hdfs_entries.create({:hadoop_instance => self, :path => "/", :is_directory => true}, { :without_protection => true }) end def self.type_name 'Instance' end def online? state == "online" end end
class WorkspacePresenter < Presenter delegate :id, :name, :summary, :owner, :archiver, :archived_at, :public, :image, :sandbox, :permissions_for, :has_added_member, :has_added_workfile, :has_added_sandbox, :has_changed_settings, to: :model def to_hash if rendering_activities? { :id => id, :name => h(name) } else { :id => id, :name => h(name), :summary => sanitize(summary), :owner => present(owner), :archiver => present(archiver), :archived_at => archived_at, :public => public, :image => present(image), :permission => permissions_for(current_user), :has_added_member => has_added_member, :has_added_workfile => has_added_workfile, :has_added_sandbox => has_added_sandbox, :has_changed_settings => has_changed_settings, :sandbox_info => present(sandbox) }.merge(latest_comments_hash) end end def complete_json? !rendering_activities? end private def latest_comments_hash return {} unless @options[:show_latest_comments] recent_notes = model.owned_notes.recent recent_comments = model.comments.recent recent_insights = recent_notes.where(:insight => true) recent_notes_and_comments = recent_notes.order("updated_at desc").limit(5) + recent_comments.order("updated_at desc").limit(5) latest_5 = recent_notes_and_comments.sort_by(&:updated_at).last(5) { :number_of_insights => recent_insights.size, :number_of_comments => recent_notes.size + recent_comments.size - recent_insights.size, :latest_comment_list => present(latest_5) } end end
require './helpers/persistence_handler' class VagrantControl FILENAME = 'Vagrantfile' def initialize @persistence_handler = PersistenceHandler.new end def log_path? @persistence_handler.logfile?.value end def startup_command? ('vagrant up >> ' + log_path?) end def login_command? ('vagrant ssh >> ' + log_path?) end def destroy_command? ('vagrant destroy -f >> ' + log_path?) end def share_command? ('vagrant share --ssh>> ' + log_path?) end def create_file(machine_name) write_option = 'w' image = @persistence_handler.machine_image?(machine_name) url = image.url ip = @persistence_handler.machine_ip?(machine_name) path = @persistence_handler.vm_installpath?.value.concat(machine_name) << '/' path_file = path.concat(FILENAME) open(path_file, write_option) { |i| i.write("Vagrant.configure(\"2\") do |conf|\n") i.write("\t" + 'conf.vm.box' + ' = ' + "\"#{image.vm_name}\"" + "\n") i.write("\t" + 'conf.vm.box_url' + ' = ' + "\"#{url}\"" + "\n") i.write("\t" + 'conf.vm.network :private_network, ip: ' + "\"#{ip}\"" + "\n" + "\n") i.write("\t" + 'conf.vm.provision "ansible" do |ansible|'+ "\n") i.write("\t" + 'ansible.playbook = "' + machine_name + '.yaml"'+ "\n") i.write("\t" + 'end' + "\n" + "\n") i.write("\t" + 'conf.vm.provider :virtualbox do |vb|'+ "\n") i.write("\t" + 'vb.name = ' + "\"#{machine_name}\"" + "\n") i.write("\t" + 'end'+ "\n" + "\n") i.write('end') } end end
module Extensions module Authenticatable def self.included(base) base.class_eval do ############# CONFIGURATION ############# # Include default devise modules. Others available are: # :token_authenticatable, :omniauthable devise :database_authenticatable, :registerable, :confirmable, :lockable, :timeoutable, :recoverable, :rememberable, :trackable, :validatable ## ATTRIBUTE PROTECTION attr_accessible :password, :password_confirmation, :remember_me, :confirmation_token ############ PUBLIC METHODS ############# # Don't require password if not confirmed def password_required? super if confirmed? end # Ensure passwords match def password_match? self.errors[:password] << "can't be blank" if password.blank? self.errors[:password_confirmation] << "can't be blank" if password_confirmation.blank? self.errors[:password_confirmation] << "does not match password" if password != password_confirmation password == password_confirmation && !password.blank? end end end end end
class ConfirmationMailer < ActionMailer::Base def confirm_email(target_email,activation_token) @activation_token = activation_token mail(to: target_email, body:"http://localhost:3000/sessions/#{@activation_token}/edit", content_type:"text/html", subject: "text confirmation", template_path: "confirmation_mailer", tamplate_name: "confirm_email") end end
require 'rails_helper' RSpec.describe HomeController, :type => :controller do let(:user) { FactoryGirl.create(:user) } describe "get index page" do describe "with no session" do before { get :index } it "should redirect to sign_in page" do expect(response).to redirect_to new_user_session_path end end describe "with valid session" do before { sign_in user } before { get :index } it "should redirect to home page" do expect(response).to be_success end end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{vertica} s.version = "0.8.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jeff Smick", "Matt Bauer"] s.date = %q{2010-08-17} s.description = %q{Query Vertica with ruby} s.email = %q{sprsquish@gmail.com} s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ "LICENSE", "README.md", "Rakefile", "VERSION", "lib/vertica.rb", "lib/vertica/bit_helper.rb", "lib/vertica/column.rb", "lib/vertica/connection.rb", "lib/vertica/core_ext/numeric.rb", "lib/vertica/core_ext/string.rb", "lib/vertica/messages/backend_messages/authentication.rb", "lib/vertica/messages/backend_messages/backend_key_data.rb", "lib/vertica/messages/backend_messages/bind_complete.rb", "lib/vertica/messages/backend_messages/close_complete.rb", "lib/vertica/messages/backend_messages/command_complete.rb", "lib/vertica/messages/backend_messages/data_row.rb", "lib/vertica/messages/backend_messages/empty_query_response.rb", "lib/vertica/messages/backend_messages/error_response.rb", "lib/vertica/messages/backend_messages/no_data.rb", "lib/vertica/messages/backend_messages/notice_response.rb", "lib/vertica/messages/backend_messages/notification_response.rb", "lib/vertica/messages/backend_messages/parameter_description.rb", "lib/vertica/messages/backend_messages/parameter_status.rb", "lib/vertica/messages/backend_messages/parse_complete.rb", "lib/vertica/messages/backend_messages/portal_suspended.rb", "lib/vertica/messages/backend_messages/ready_for_query.rb", "lib/vertica/messages/backend_messages/row_description.rb", "lib/vertica/messages/backend_messages/unknown.rb", "lib/vertica/messages/frontend_messages/bind.rb", "lib/vertica/messages/frontend_messages/cancel_request.rb", "lib/vertica/messages/frontend_messages/close.rb", "lib/vertica/messages/frontend_messages/describe.rb", "lib/vertica/messages/frontend_messages/execute.rb", "lib/vertica/messages/frontend_messages/flush.rb", "lib/vertica/messages/frontend_messages/parse.rb", "lib/vertica/messages/frontend_messages/password.rb", "lib/vertica/messages/frontend_messages/query.rb", "lib/vertica/messages/frontend_messages/ssl_request.rb", "lib/vertica/messages/frontend_messages/startup.rb", "lib/vertica/messages/frontend_messages/sync.rb", "lib/vertica/messages/frontend_messages/terminate.rb", "lib/vertica/messages/message.rb", "lib/vertica/notice.rb", "lib/vertica/notification.rb", "lib/vertica/result.rb", "lib/vertica/vertica_socket.rb" ] s.homepage = %q{http://github.com/sprsquish/vertica} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Pure ruby library for interacting with Vertica} s.test_files = [ "test/connection_test.rb", "test/test_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
class EndecaRecordChange < ActiveRecord::Base #### # MODEL ANNOTATIONS #### extend ValidationHelper #### # VALIDATORS #### validates_presence_of :review_id validates_presence_of :product_id enum_validator :change, [:replace, :delete] enum_validator :status, [:new, :processing, :success, :fail] before_create :remove_opposites def remove_opposites EndecaRecordChange.delete_all("review_id = #{review_id} AND status='new' AND endeca_record_changes.change = '#{change == :replace ? 'delete' : 'replace'}'") end def EndecaRecordChange.create_record(review, event) create!(:review_id => review.id, :product_id => review.product_id, :change => event.event_type, :status => :new) end end
class ChargesController < ApplicationController before_action :authenticate_user! def free project = Project.find(params[:project_id]) current_user.subscriptions.create(project: project) redirect_to project end def create project = Project.find(params[:project_id]) # Create the customer in Stripe customer = Stripe::Customer.create( email: params[:stripeEmail], source: params[:stripeToken] ) # Create the charge using the customer data returned by Stripe API charge = Stripe::Charge.create( customer: customer.id, amount: project.price, description: project.name, currency: 'jpy' ) if charge current_user.subscriptions.create(project: project) redirect_to project end rescue Stripe::CardError => e flash[:error] = e.message redirect_to project end end
require "application_system_test_case" class ErrorsTest < ApplicationSystemTestCase test "visit 404 page" do visit '404' assert_text '404' end test "visit 422 page" do visit '422' assert_text '422' end test "visit 500 page" do visit '500' assert_text '500' end end
Rails.application.routes.draw do resources :places devise_for :users, controllers: { registrations: 'registrations', passwords: 'passwords' }, path: '', path_names: { confirmation: 'verification', unlock: 'unlock', sign_in: 'login', sign_out: 'logout', sign_up: 'sign_up' } resources :users resources :roles root to: 'home#index' end
class Post < ApplicationRecord belongs_to :user belongs_to :zemi has_many :favorites default_scope -> { order(created_at: :desc)} validates :title, presence: true validates :member, presence: true validates :research_title, presence: true validates :research_content, presence: true validates :application, presence: true validates :junior_content, presence: true validates :senior_content, presence: true validates :trip_selection, presence: true validates :extra_selection, presence: true validates :extra_active, presence: true def favorited_by?(user) favorites.where(user_id: user.id).exists? end end
require 'rubygems' require 'ruby-processing' class Sketch<Processing::App def setup size 200,200 background 255 smooth end def draw r, g, b, a = random(255), random(255), random(255), random(255) diam = random(20) x, y = random(width), random(height) no_stroke fill r, g, b, a ellipse x, y, diam, diam end def mouse_pressed stroke 0 fill 255,0,0,255 rect_mode CENTER rect mouse_x, mouse_y, 5, 5 end Sketch.new :title => "My Sketch" end
class PokeLoc < ApplicationRecord include Mongoid::Document include Mongoid::Timestamps include Location include PokemonRef field :tol, type: Time field :pop2nd, type: Boolean field :iv_a, type: Integer field :iv_d, type: Integer field :iv_s, type: Integer field :weight, type: Float field :height, type: Float field :gender, type: Integer field :key, type: String field :area_ids, type: Array index({location: "2dsphere", tol: -1}, unique: true) index({key: 1}, unique: true) validates_presence_of :pokemon_id validates_presence_of :lat validates_presence_of :lng before_save :generate_key def generate_key if self.pokemon_id.nil? || self.tol.nil? self.lat.nil? || self.lng.nil? self.key = nil else self.key = sprintf("%d-%d-%.7f-%.7f", self.pokemon_id, self.tol.beginning_of_hour, self.lat, self.lng) end end def iv_rate if iv_a && iv_d && iv_s (100.0 * (iv_a + iv_d + iv_s) / 45.0).round else nil end end def same?(other) self.attributes.except("id", "created_at", "updated_at") == other.attributes.except("id", "created_at", "updated_at") end def self.lookup(loc) SpawnLoc.where(key: loc.key).first end def self.current_list(lat:, lng:) ret = PokeLoc.where(tol: {"$gte": Time.now}).limit(10000).geo_near({type: "Point", coordinates: [lng, lat]}).spherical.max_distance(50000) logger.info("current_list num=#{ret.count}") ret end end
# Application controller # Base for all controllers class ApplicationController < ActionController::Base include Pundit protect_from_forgery with: :exception before_action :require_login, :set_locale, :set_paper_trail_whodunnit responders :flash def self.default_url_options { locale: I18n.locale } end def not_authenticated redirect_to login_path end private def set_locale I18n.locale = params[:locale] || I18n.default_locale end end
class CategoriesController < ApplicationController before_filter :admin_required, :except => [:index, :show] add_breadcrumb I18n.t('title.categories'), :categories_path def index @categories = Category.all end def new add_breadcrumb I18n.t('title.add_category'), :new_category_path @category = Category.new end def create @category = Category.new(params[:category]) if @category.save redirect_to categories_url, :flash => { :success => I18n.t('notice.category_created') } else render :new end end def show @category = Category.find_by_name(params[:id]) raise ActiveRecord::RecordNotFound unless @category @ads = Ad.find_by_tag_ids(@category.tags.select('tags.id')) add_breadcrumb @category.name, category_path(@category) end def edit @category = Category.find_by_name(params[:id]) add_breadcrumb @category.name, category_path(@category) end def update @category = Category.find_by_name(params[:id]) if @category.update_attributes(params[:category]) redirect_to categories_url, :flash => { :success => I18n.t('notice.category_updated') } else render :edit end end def destroy @category = Category.find(params[:id]) @category.destroy redirect_to categories_url end end
require( 'minitest/autorun' ) require( 'minitest/rg') require_relative( '../song.rb') class TestSong < MiniTest::Test def setup @song = Song.new(1, "The Gambler", "Kenny Rogers") end def test_song_can_be_created assert_equal(Song, @song.class) end def test_get_track_id assert_equal(1, @song.track_id) end def test_get_track_name assert_equal("The Gambler", @song.track_name) end def test_get_artist assert_equal("Kenny Rogers", @song.artist) end end
module QueryMethodsExtend module OrExtend @is_query_or = false def set_is_query_or value @is_query_or = value if self.where_values.size > 0 self end def where!(opts, *rest) if Hash === opts opts = sanitize_forbidden_attributes(opts) references!(ActiveRecord::PredicateBuilder.references(opts)) end if @is_query_or set_is_query_or false self.where_values = ["(#{build_string_where(self.where_values)}) OR (#{build_string_where(build_where(opts, rest))})"] else self.where_values += build_where(opts, rest) end self end def build_string_where where_data where_data.map{ |data| data.class == String ? data : data.to_sql }.join(' AND ') end end module OrQuery extend ActiveSupport::Concern included do def self.or agrs = nil if agrs if agrs.class == Hash act = self.unscoped.where(agrs).where_values.map{ |data| data.to_sql }.join(' OR ') self.where("(#{act})") else raise 'Agruments should be a HASH' end else all.extending(OrExtend).set_is_query_or(true) end end end end end
class Lost < ActiveRecord::Base belongs_to :category belongs_to :user has_many :comments, :as => :commentable validates_presence_of :title validates_presence_of :location mount_uploader :lost_img, StuffImageUploader include PgSearch pg_search_scope :search, :against => [:name, :location, :description], :using => { :tsearch => {:prefix => true}} end
require 'pathname' module RhevmDescriptor def d_init # Make sure this is a descriptor. desc, defs = parseDescriptor(dInfo.Descriptor) # Make sure each disk is there. defs.each do|diskDef| filename = buildFilename(diskDef[:filename]) raise "No disk file: #{filename}" unless File.exist?(filename) end # Init needed stff. self.diskType = "Rhevm Descriptor" self.blockSize = 512 @desc = desc # This disk descriptor. @defs = defs # Disk extent definitions. @ostructs = [] # Component OpenStructs for disk objects. @disks = [] # Component MiqDisk objects (one for each disk). # If there's a parent parse it first (all subordinate disks need a ref to parent). if desc.key?(:puuid) && desc[:puuid] != '00000000-0000-0000-0000-000000000000' @parentOstruct = OpenStruct.new # Get the parentFileNameHint and be sure it is relative to the descriptor file's directory parentFileName = buildFilename(desc[:puuid]) # puts "#{self.class.name}: Getting parent disk file [#{parentFileName}]" @parentOstruct.fileName = parentFileName @parentOstruct.mountMode = dInfo.mountMode @parentOstruct.hardwareId = dInfo.hardwareId if dInfo.baseOnly d = MiqDisk.getDisk(@parentOstruct) raise "MiqDisk#getDisk returned nil for parent disk #{@parentOstruct.fileName}" if d.nil? @parent = d return if dInfo.baseOnly end # Instance MiqDisks for each disk definition. defs.each do |diskDef| thisO = OpenStruct.new thisO.Descriptor = dInfo.Descriptor if dInfo.Descriptor thisO.parent = @parent thisO.fileName = buildFilename(diskDef[:filename]) thisO.offset = diskDef[:offset] thisO.rawDisk = true if diskDef[:format].to_s.include?('RAW') thisO.mountMode = dInfo.mountMode @ostructs << thisO d = MiqDisk.getDisk(thisO) raise "MiqDisk#getDisk returned nil for component disk #{thisO.fileName}" if d.nil? @disks << d end end def getBase @parent || self end def d_read(pos, len) # $log.debug "RhevmDescriptor.d_read << pos #{pos} len #{len}" if $log && $log.debug? # Get start and end extents. dStart = getTargetDiskIndex((pos / @blockSize).ceil) dEnd = getTargetDiskIndex(((pos + len) / @blockSize).ceil) if dStart == dEnd # Case: single extent. retBytes = @disks[dStart].d_read(pos, len, getDiskByteOffset(dStart)) else # Case: span extents. retBytes = ""; bytesRead = 0 dStart.upto(dEnd) do |diskIdx| readLen = @disks[diskIdx].d_size # Adjust length for start and end extents. readLen -= pos if diskIdx == dStart readLen -= (len - bytesRead) if diskIdx == dEnd # Read. retBytes << @disks[diskIdx].d_read(pos + bytesRead, readLen, getDiskByteOffset(diskIdx)) bytesRead += readLen end end # $log.debug "RhevmDescriptor.d_read >> retBytes.length #{retBytes.length}" if $log && $log.debug? retBytes end def d_write(pos, buf, len) dStart = getTargetDiskIndex((pos / @blockSize).ceil) dEnd = getTargetDiskIndex(((pos + len) / @blockSize).ceil) # Case: single extent. return @disks[dStart].d_write(pos, buf, len, getDiskByteOffset(dStart)) if dStart == dEnd # Case: span extents. bytesWritten = 0 dStart.upto(dEnd) do |diskIdx| writeLen = @disks[diskIdx].d_size # Adjust length for start and end extents. writeLen -= pos if diskIdx == dStart writeLen -= (len - bytesWritten) if diskIdx == dEnd # Write. bytesWritten += @disks[diskIdx].d_write(pos + bytesWritten, writeLen, getDiskByteOffset(diskIdx)) end bytesWritten end # Close all disks. def d_close @parent.close unless @parent.nil? @disks.each(&:close) end # Return size in sectors. def d_size @desc[:size].to_i end # Get target disk index based on sector number. def getTargetDiskIndex(sector) dIdx = -1; total = 0 0.upto(@defs.size - 1) do|idx| total += @defs[idx][:size].to_i if total >= sector dIdx = idx break end end raise "Sector is past end of disk: #{sector}" if dIdx == -1 raise "Disk object is nil for #{sector}" if @disks[dIdx].nil? dIdx end # Get beginning byte offset of target disk. def getDiskByteOffset(target) total = 0 0.upto(@defs.size - 1) do|idx| break if idx == target total += @defs[idx]['size'].to_i end total * @blockSize end def parseDescriptor(descriptor) desc = {} descriptor.each_line do |line| line.strip! break if line == 'EOF' next unless line.include?('=') key, *value = line.split('=') desc[key.downcase.to_sym] = value = value.join('=') end desc[:offset] = 0 desc[:filename] = File.basename(dInfo.fileName) return desc, [desc] end def buildFilename(parent_uuid) parentFileName = Pathname.new(parent_uuid) if parentFileName.absolute? parentFileName = parentFileName.relative_path_from(Pathname.new(dInfo.fileName).dirname) $log.debug "#{self.class.name}: Parent disk file is absolute. Using relative path [#{parentFileName}]" if $log end File.join(File.dirname(dInfo.fileName), parentFileName.to_s.tr("\\", "/")) end end # module RhevmDescriptor
require "application_system_test_case" class MealPlansTest < ApplicationSystemTestCase setup do @meal_plan = meal_plans(:one) end test "visiting the index" do visit meal_plans_url assert_selector "h1", text: "Meal Plans" end test "creating a Meal plan" do visit meal_plans_url click_on "New Meal Plan" fill_in "Notes", with: @meal_plan.notes fill_in "Start date", with: @meal_plan.start_date fill_in "User", with: @meal_plan.user_id click_on "Create Meal plan" assert_text "Meal plan was successfully created" click_on "Back" end test "updating a Meal plan" do visit meal_plans_url click_on "Edit", match: :first fill_in "Notes", with: @meal_plan.notes fill_in "Start date", with: @meal_plan.start_date fill_in "User", with: @meal_plan.user_id click_on "Update Meal plan" assert_text "Meal plan was successfully updated" click_on "Back" end test "destroying a Meal plan" do visit meal_plans_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Meal plan was successfully destroyed" end end
require './lib/craft' # # class Person attr_reader :name, :interests, :supplies def initialize(info) @name = info[:name] @interests = info[:interests] @supplies = {} end def add_supply(material, quantity) @supplies[material] ||= 0 @supplies[material] += quantity end def can_build?(craft) tru = 0 fals = 0 # require "pry"; binding.pry craft.supplies_required.each_pair do |material, quantity| if @supplies.keys.include?(material.to_s) && quantity >= @supplies[material] tru += 1 else fals += 1 end end if tru >= fals true else false end end end
require 'logger' require 'utilrb/logger' module Orocos def self.log_all log_all_ports log_all_configuration end # Setup logging on all output ports of the processes started with Orocos.run # # This method is designed to be called within an Orocos.run block # # @param [nil,#===] exclude_ports an object matching the name of the ports # that should not be logged (typically a regular expression). If nil, all # ports are logged. # @param [nil,#===] exclude_types an object matching the name of the types # that should not be logged (typically a regular expression). If nil, all # ports are logged. # @param [nil,Array<String>] tasks name of the tasks for which logging # should be set up # # @example log all ports whose name does not start with 'io_' # Orocos.log_all_ports(exclude_ports: /^io_/) # @example log all ports whose type name does not contain 'debug' # Orocos.log_all_ports(exclude_types: /debug/) # def self.log_all_ports(exclude_ports: nil, exclude_types: nil, tasks: nil) each_process do |process| process.log_all_ports(exclude_ports: exclude_ports, exclude_types: exclude_types, tasks: tasks) end end class << self attr_accessor :configuration_log_name end @configuration_log_name = "properties" # The Pocolog::Logfiles object used by default by # Orocos.log_all_configuration. It will automatically be created by # Oroocs.configuration_log if Orocos.log_all_configuration is called without # an argument attr_writer :configuration_log # If Orocos.configuration_log is not set, it creates a new configuration log # file that will be used by default by Orocos.log_all_configuration. The log # file is named as Orocos.configuration_log_name ('task_configuration' by # default). This log file becomes the new default log file for all following # calls to Orocos.log_all_configuration def self.configuration_log if !HAS_POCOLOG raise ArgumentError, "the pocolog Ruby library is not available, configuration logging cannot be used" end @configuration_log ||= Pocolog::Logfiles.create(File.expand_path(Orocos.configuration_log_name, Orocos.default_working_directory)) end def self.log_all_configuration(logfile = nil) logfile ||= configuration_log each_process do |process| process.each_task do |t| t.log_all_configuration(logfile) end end end # Common implementation of log_all_ports for a single process # # This is shared by local and remote processes alike def self.log_all_process_ports(process, tasks: nil, exclude_ports: nil, exclude_types: nil, **logger_options) if !(logger = process.default_logger) return Set.new end process.setup_default_logger( logger, **logger_options) logged_ports = Set.new process.task_names.each do |task_name| task = process.task(task_name) next if task == logger next if tasks && !(tasks === task_name) task.each_output_port do |port| next if exclude_ports && exclude_ports === port.name next if exclude_types && exclude_types === port.type.name next if block_given? && !yield(port) Orocos.info "logging % 50s of type %s" % ["#{task.name}:#{port.name}", port.type.name] logged_ports << [task.name, port.name] logger.log(port) end end if logger.pre_operational? logger.configure end if !logger.running? logger.start end logged_ports end end
require 'spec_helper_acceptance' case fact('osfamily') when 'RedHat' package_name = 'elasticsearch' service_name = 'elasticsearch' when 'Debian' package_name = 'elasticsearch' service_name = 'elasticsearch' when 'Suse' package_name = 'elasticsearch' service_name = 'elasticsearch' end if fact('osfamily') != 'Suse' describe "module removal" do it 'should run successfully' do pp = "class { 'elasticsearch': ensure => 'absent' }" apply_manifest(pp, :catch_failures => true) end describe file('/etc/elasticsearch') do it { should_not be_directory } end describe package(package_name) do it { should_not be_installed } end describe port(9200) do it { should_not be_listening } end describe service(service_name) do it { should_not be_enabled } it { should_not be_running } end end end
class Food < ApplicationRecord include FoodSearchable has_many :categories_foods has_many :categories, through: :categories_foods has_one :food_information, inverse_of: :food belongs_to :source belongs_to :user enum status: { pending: :pending, published: :published, unpublished: :unpublished } end
require "aethyr/core/actions/commands/put" require "aethyr/core/registry" require "aethyr/core/input_handlers/command_handler" module Aethyr module Core module Commands module Put class PutHandler < Aethyr::Extend::CommandHandler def self.create_help_entries help_entries = [] command = "put" see_also = ["LOOK", "TAKE", "OPEN"] syntax_formats = ["PUT [object] IN [container]"] aliases = nil content = <<'EOF' Puts an object in a container. The container must be open to do so. EOF help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases)) return help_entries end def initialize(player) super(player, ["put"], help_entries: PutHandler.create_help_entries) end def self.object_added(data) super(data, self) end def player_input(data) super(data) case data[:input] when /^put((\s+(\d+)\s+)|\s+)(\w+)\s+in\s+(\w+)$/i $manager.submit_action(Aethyr::Core::Actions::Put::PutCommand.new(@player, { :item => $4, :count => $3.to_i, :container => $5 })) end end private end Aethyr::Extend::HandlerRegistry.register_handler(PutHandler) end end end end
class Mailer < ActionMailer::Base default from: "admin@globalnames.org" def queue_email(upload) @upload = upload mail(:to => @upload.email, :subject => "Global Names PostBox upload") do |format| format.html format.text end end def preview_email(upload) @upload = upload mail(:to => @upload.email, :subject => "Global Names PostBox preview") do |format| format.html format.text end end def error_email(upload) @upload = upload mail(:to => @upload.email, :subject => "Global Names PostBox processing error") do |format| format.html format.text end end def contact_email(contact) @contact = contact mail(:from => @contact.email, :to => Postbox::Application.config.default_admin_email, :subject => "Global Names PostBox contact submission") do |format| format.html format.text end end end
require 'rails_helper' describe 'maps' do context 'categories with addresses' do before do bob = Admin.create(email: 'a@example.com', password: '12345678', password_confirmation: '12345678') login_as bob visit '/categories/new' fill_in 'Title', with: 'Pic1' fill_in 'Description', with: 'Lorem Ipsum' attach_file 'Image', Rails.root.join('spec/images/paintedicon.jpeg') fill_in 'Url', with: 'http://www.paintedltd.co.uk' fill_in 'Address', with: '25 City Road, London' click_button 'Submit' end it 'displays a map (needs internet)', js:true do visit '/categories' click_link 'Map' expect(page).to have_css '.gm-style' end end end
module CollectionsHelper def disable_collection_button(collection = nil) conditions = collection.disabled || collection.disabled == nil if collection if conditions text = ' Enable' css_class = "btn-success fa fa-check-circle" else text = ' Disable' css_class = "btn-danger fa fa-ban" end link_to disable_toggle_collection_path(collection.id), class: "btn btn-mini #{css_class}", method: 'post', remote: true, confirm: t('collections.confirm_disable'), id: "btn_disable_#{collection.id}" do content_tag :span, text, class: 'open-san' end end def text_disabled(is_disable) case is_disable when true content_tag(:span, " Disabled", class: "label label-important") when false content_tag(:span, " Enabled", class: "label label-success") else content_tag(:span, " New", class: "label label-warning") end end def remove_collection_button(collection) link_to destroy_collection_collections_path(collection.id), class: "btn btn-default fa fa-minus-circle", method: 'post', confirm: t('collections.confirm_remove'), id: "btn_remove_#{collection.id}" do content_tag :span, 'Delete', class: 'open-san' end end def remove_collection_restaurant_button(collection, restaurant) link_to remove_restaurant_collection_path(id: collection.id, restaurant_id: restaurant.id), class: "btn btn-default fa fa-minus-circle", method: 'post', remote: true, confirm: t('collections.confirm_remove_restaurant'), id: "btn_remove_#{restaurant.id}" do content_tag :span, 'Delete', class: 'open-san' end end end
require 'test_helper' class JugadalotsControllerTest < ActionDispatch::IntegrationTest setup do @jugadalot = jugadalots(:one) end test "should get index" do get jugadalots_url assert_response :success end test "should get new" do get new_jugadalot_url assert_response :success end test "should create jugadalot" do assert_difference('Jugadalot.count') do post jugadalots_url, params: { jugadalot: { monto: @jugadalot.monto, n1: @jugadalot.n1, n2: @jugadalot.n2, n3: @jugadalot.n3, qpt: @jugadalot.qpt, sorteo: @jugadalot.sorteo, ticket: @jugadalot.ticket } } end assert_redirected_to jugadalot_url(Jugadalot.last) end test "should show jugadalot" do get jugadalot_url(@jugadalot) assert_response :success end test "should get edit" do get edit_jugadalot_url(@jugadalot) assert_response :success end test "should update jugadalot" do patch jugadalot_url(@jugadalot), params: { jugadalot: { monto: @jugadalot.monto, n1: @jugadalot.n1, n2: @jugadalot.n2, n3: @jugadalot.n3, qpt: @jugadalot.qpt, sorteo: @jugadalot.sorteo, ticket: @jugadalot.ticket } } assert_redirected_to jugadalot_url(@jugadalot) end test "should destroy jugadalot" do assert_difference('Jugadalot.count', -1) do delete jugadalot_url(@jugadalot) end assert_redirected_to jugadalots_url end end
=begin PEDAC Data structure Input: string Output: Boolen Create a hash with letters of the laphabet and corresponding blocks Algorithm iterate throught the letters of the word Use the hash to find the corresponding block Push the block into an array Compare the array with the unique version of the array =end SPELLING_BLOCKS = { B: 'B:O', O: 'B:O', X: 'X:K', K: 'X:K', D: 'D:Q', Q: 'D:Q', C: 'C:P', P: 'C:P', N: 'N:A', A: 'N:A', G: 'G:T', T: 'G:T', R: 'R:E', E: 'R:E', F: 'F:S', S: 'F:S', J: 'J:W', W: 'J:W', H: 'H:U', U: 'H:U', V: 'V:I', I: 'V:I', L: 'L:Y', Y: 'L:Y', Z: 'Z:M', M: 'Z:M' } def block_word?(string) array = [] string.each_char do |letter| array << SPELLING_BLOCKS[letter.upcase.to_sym] end array == array.uniq end puts block_word?('BATCH') == true puts block_word?('BUTCH') == false puts block_word?('jest') == true # 2019-06-01 SPELLING_BLOCKS = %w(B:O X:K D:Q C:P N:A G:T R:E F:S J:W H:U V:I L:Y Z:M) SPELLING_HASH = {} SPELLING_BLOCKS.each do |block| SPELLING_HASH[block[0].to_sym] = block SPELLING_HASH[block[2].to_sym] = block end def block_word?(word) array = word.chars.map do |letter| SPELLING_HASH[letter.upcase.to_sym] end array.uniq == array end puts block_word?('BATCH') == true puts block_word?('BUTCH') == false puts block_word?('jest') == true
class CreateFeedUpdates < ActiveRecord::Migration def change create_table :feed_updates do |t| t.integer :user_id, null: false t.integer :entry_id, null: false t.string :entry_type t.timestamps end add_index :feed_updates, :user_id end end
require 'spec_helper' describe AvatarHelper do before(:all) do @me = Factory.build(:normal_person, :first_name => "My", :last_name => "Self") @me.id = 1 @registered_user = Factory.build(:registered_user, :first_name => "Someone", :last_name => "Else", :id => 13) @registered_user.id = 13 @invalid_registered_user = Factory.build(:registered_user, :first_name => "Someone", :last_name => "Bad") @invalid_registered_user.id = 4 @amazon_config = YAML.load_file( File.join(Rails.root, "config", "amazon_s3.yml"))[Rails.env] end context "link to profile" do it "should link to my private page" do helper.stub(:current_person).and_return(@me) # helper.should_receive(:user_profile).and_return("/user/") helper.link_to_profile(@me) do "blah" end.should =~ /\<a href="\S*\/user\/1" title="My Self">blah<\/a>/i end it "should like to go to a persons public page" do helper.stub(:current_person).and_return(@registered_user) # helper.should_receive(:user_profile).and_return("/user/13") helper.link_to_profile(@registered_user) do "blah" end.should =~ /\<a href="\S*\/user\/13" title="Someone Else">blah<\/a>/i end end context "text profile" do it "should display a users name with a link" do helper.stub(:current_person).and_return(@me) # helper.should_receive(:user_profile).with("user/#{@registered_user.id}").and_return("/user/#{@registered_user.id}") @registered_user.avatar.url(:standard).gsub(/\?\d*/, '').should == "http://s3.amazonaws.com/#{@amazon_config['bucket']}/avatars/13/standard/test_image.jpg" @registered_user.avatar.stub(:url).and_return("http://avatar_url") helper.text_profile(@registered_user).should =~ /\<a href="\S*\/user\/13" title="Someone Else">Someone Else<\/a>/i end end context "profile image" do it "should display a profile image with the default size" do @me.avatar.url(:standard).gsub(/\?\d*/, '').should == "http://s3.amazonaws.com/#{@amazon_config['bucket']}/avatars/1/standard/test_image.jpg" @me.avatar.stub(:url).and_return("http://avatar_url") helper.profile_image(@me).should == "<img alt=\"My Self\" height=\"20\" src=\"http://avatar_url\" title=\"My Self\" width=\"20\" />" end it "should display a profile image with a size of 80" do @me.avatar.stub(:url).and_return("http://avatar_url") helper.profile_image(@me, 80).should == "<img alt=\"My Self\" height=\"80\" src=\"http://avatar_url\" title=\"My Self\" width=\"80\" />" end end context "avatar profile" do context "should display a profile image with a size of 80" do it "when there is no PA ID" do @me.avatar.stub(:url).and_return("http://avatar_url") helper.profile_image(@me, 80).should == "<img alt=\"My Self\" height=\"80\" src=\"http://avatar_url\" title=\"My Self\" width=\"80\" />" end end end end
movies = { matrix: 5, avengers: 5, captain_marvel: 5 } puts "Enter a Choice, add, update, display, delete" choice = gets.chomp case choice when "add" puts "Enter a Movie Title" title = gets.chomp puts "Enter Rating for Movie" rating = gets.chomp if (movies[title.to_sym] == nil) movies[title.to_sym] = rating.to_i puts "added" else puts "Movie already exists" end when "update" puts "Enter a Movie Title" title = gets.chomp if(movies[title.to_sym] == nil) puts "Movie not added" else puts "Enter new rating" rating = gets.chomp movies[title.to_sym] = rating.to_i end when "display" movies.each {|movie, rating| puts "#{movie}: #{rating}"} when "delete" puts "Enter name of movie to delete" title = gets.chomp if(movies[title.to_sym] == nil) puts "Movie not added" else movies.delete(title) puts "Movie deleted" end else puts "Error! Please enter a valid choice of add, update, display, delete" end
class EmployeesController < ApplicationController before_action :set_employee, only: [:show, :destroy] def index @employee = Employee.new @employees = Employee.all end def show end def create @employee = Employee.new(employee_params) if @employee.save render json: @employee, status: :ok else render json: @employee.errors.full_messages, status: :unprocessable_entity end end def update end def destroy if @employee.destroy head :no_content end end private def set_employee @employee = Employee.find(params[:id]) end def employee_params params.require(:employee).permit(:first_name, :last_name, :address, :phone, :birthdate) end end
class User < ApplicationRecord has_secure_password validates :first_name, :last_name, :username, :password_digest, presence: true validates :username, uniqueness: true end
require 'spec_helper' require 'active_fedora/registered_attributes' describe 'ActiveFedora::RegisteredAttributes' do class MockDelegateAttribute < ActiveFedora::Base include ActiveFedora::RegisteredAttributes has_metadata :name => "properties", :type => ActiveFedora::SimpleDatastream do |m| m.field "title", :string m.field "description", :string m.field "creator", :string m.field "file_names", :string m.field "locations", :string m.field "created_on", :date m.field "modified_on", :date end attribute :title, { datastream: 'properties', label: 'Title of your Work', hint: "How would you name this?", validates: { presence: true } } attribute :description, { datastream: 'properties', default: ['One two'], multiple: true } attribute :creator, { datastream: 'properties', multiple: false, writer: lambda{|value| value.reverse } } attribute :file_names, { datastream: 'properties', multiple: true, writer: lambda{|value| value.reverse } } def set_locations(value) value.dup << '127.0.0.1' end protected :set_locations attribute :locations, { datastream: 'properties', displayable: false, multiple: true, writer: :set_locations } attribute :created_on, { datastream: 'properties', multiple: false, reader: lambda {|value| "DATE: #{value}" } } attribute :not_in_the_datastream, { multiple: false, editable: false, displayable: false } attribute :modified_on, { datastream: 'properties', multiple: true, editable: false, reader: lambda {|value| "DATE: #{value}" } } end class ChildModel < MockDelegateAttribute attribute :not_on_parent end subject { MockDelegateAttribute.new() } describe '.registered_attribute_names' do let(:expected_attribute_names) { ["title", "description", "creator", "file_names", "locations", "created_on", "not_in_the_datastream", "modified_on"] } it { expect(MockDelegateAttribute.registered_attribute_names).to eq( expected_attribute_names ) } end describe '#editable_attributes' do let(:expected_attribute_names) { [ :title, :description, :creator, :file_names, :locations, :created_on ] } it 'is all of the attributes that are editable' do actual_editable_attributes = subject.editable_attributes.collect {|a| a.name } expect(actual_editable_attributes).to eq(expected_attribute_names) expect(subject.terms_for_editing).to eq(expected_attribute_names) end end describe '.editable_attributes' do it 'delegates to the .attribute_registry' do expected_editable_attributes = MockDelegateAttribute.attribute_registry.editable_attributes expect(MockDelegateAttribute.editable_attributes).to eq expected_editable_attributes end end describe '.displayable_attributes' do it 'delegates to the .attribute_registry' do expected_displayable_attributes = MockDelegateAttribute.attribute_registry.displayable_attributes expect(MockDelegateAttribute.displayable_attributes).to eq expected_displayable_attributes end end describe '#displayable_attributes' do let(:expected_attribute_names) { [ :title, :description, :creator, :file_names, :created_on, :modified_on ] } it 'is all of the attributes that are displayable' do actual_displayable_attributes = subject.displayable_attributes.collect {|a| a.name } expect(actual_displayable_attributes).to eq(expected_attribute_names) expect(subject.terms_for_display).to eq(expected_attribute_names) end end describe '.attribute' do context 'for model inheritance' do it 'does not add child declared attributes to parent class' do expect { MockDelegateAttribute.attribute_registry.fetch(:not_on_parent) }.to raise_error(KeyError) end it 'children have parent attributes' do expect { ChildModel.attribute_registry.fetch(:title) }.to_not raise_error(KeyError) end it 'children have attribute setting from parent' do child = ChildModel.new expect { child.title = 'Hello' }.to_not raise_error(NoMethodError) end end it 'handles attributes not delegated to a datastream' do subject.not_in_the_datastream = 'World?' expect(subject.not_in_the_datastream).to eq('World?') end it "has creates a setter/getter" do subject.title = 'Hello' expect(subject.properties.title).to eq([subject.title]) end it "enforces validation when passed" do subject.title = nil subject.valid? expect(subject.errors[:title].size).to eq(1) end it "allows for default" do expect(subject.description).to eq(['One two']) end it "allows for a reader to intercept the returning of values" do date = Date.today subject.created_on = date expect(subject.properties.created_on).to eq([date]) expect(subject.created_on).to eq("DATE: #{date}") end it "allows for a reader to intercept the returning of values" do date = Date.today subject.created_on = date expect(subject.properties.created_on).to eq([date]) expect(subject.created_on).to eq("DATE: #{date}") end it "allows for a writer to intercept the setting of values" do text = 'hello world' subject.creator = 'hello world' expect(subject.properties.creator).to eq([text.reverse]) expect(subject.creator).to eq(text.reverse) end it "allows for a writer to intercept the setting of values" do values = ['foo.rb', 'bar.rb'] subject.file_names = values expect(subject.properties.file_names).to eq(values.reverse) expect(subject.file_names).to eq(values.reverse) end it "intercepts blanks and omits them" do values = ['foo.rb', '', 'bar.rb', ''] expected_values = ['foo.rb', 'bar.rb'] subject.description = values expect(subject.properties.description).to eq(expected_values) expect(subject.description).to eq(expected_values) end it "allows for a writer that is a symbol" do values = ['South Bend', 'State College', 'Minneapolis'] expected_values = values.dup expected_values << '127.0.0.1' subject.locations = values expect(subject.properties.locations).to eq(expected_values) expect(subject.locations).to eq(expected_values) end end end
require 'spec_helper' Run.tg(:read_only) do use_pacer_graphml_data(:read_only) describe Pacer::Filter::LoopFilter do describe '#loop' do it 'is a ClientError if no control block is specified' do lambda do graph.v.loop { |v| v.out }.in.to_a end.should raise_error Pacer::ClientError end it 'is a ClientError if no control block is specified' do lambda do graph.v.loop { |v| v.out }.to_a end.should raise_error Pacer::ClientError end describe 'control block' do it 'should wrap elements' do yielded = false graph.v.loop { |v| v.out }.while do |el| el.should be_a Pacer::Wrappers::VertexWrapper yielded = true end.first yielded.should be_true end it 'should wrap path elements' do yielded = false graph.v.loop { |v| v.out }.while do |el, depth, path| el.should be_a Pacer::Wrappers::VertexWrapper depth.should == 0 path.should be_a Array path.length.should == 1 path.each do |e| e.should be_a Pacer::Wrappers::VertexWrapper end yielded = true end.first yielded.should be_true end context 'project tree' do let(:depths) do [ 0, # pangloss 1, # pacer 2, 2, 2, # gremlin, pipes, blueprints 3, 3, 3, # gremlin>blueprints, gremlin>pipes, pipes>blueprints 4 # gremlin>pipes>blueprints ] end let(:route) do pangloss.loop { |v| v.out }.while do |el, depth, path| depth.should == depths.shift path.length.should == depth + 1 true end end it 'should exhaust the depths list' do route.to_a depths.should be_empty end it 'should have the right results' do route[:name].to_a.should == %w[ pangloss pacer gremlin pipes blueprints blueprints pipes blueprints blueprints ] end end let(:paths) do [ %w[ pangloss ], %w[ pangloss pacer ], %w[ pangloss pacer gremlin ], %w[ pangloss pacer pipes ], %w[ pangloss pacer blueprints ], %w[ pangloss pacer gremlin blueprints ], %w[ pangloss pacer gremlin pipes ], %w[ pangloss pacer pipes blueprints ], %w[ pangloss pacer gremlin pipes blueprints ] ] end it 'should have correct paths with control block paths' do route = pangloss. loop { |v| v.out }. while { |el, depth, path| true }. paths route.collect { |p| p.map { |e| e[:name] } }.should == paths end it 'should have correct paths without control block paths' do route = pangloss. loop { |v| v.out }. while { |el| true }. paths route.collect { |p| p.map { |e| e[:name] } }.should == paths end it 'should loop or emit or loop_and_emit as needed' do route = pangloss.loop { |v| v.out }.while do |el, depth| if el[:name] == 'pacer' :loop_and_emit elsif depth == 4 :emit else :loop end end route[:name].to_a.should == %w[ pacer blueprints ] end end end describe '#repeat' do it 'should apply the route part twice' do route = graph.v.repeat(2) { |tail| tail.out_e.in_v }.inspect route.should == graph.v.out_e.in_v.out_e.in_v.inspect end it 'should apply the route part 3 times' do route = graph.v.repeat(3) { |tail| tail.out_e.in_v }.inspect route.should == graph.v.out_e.in_v.out_e.in_v.out_e.in_v.inspect end describe 'with a range' do let(:start) { graph.vertex(0) } subject { start.repeat(1..3) { |tail| tail.out_e.in_v }[:name] } it 'should be equivalent to executing each path separately' do subject.to_a.should == [start.out_e.in_v[:name].to_a, start.out_e.in_v.out_e.in_v[:name].to_a, start.out_e.in_v.out_e.in_v.out_e.in_v[:name].to_a].flatten end end end end end
# Public: Takes two numbers and returns the potency. # # base - The Integer that will be the base. # exponent - The Integer that will be the exponent. # # Examples # # power(3, 2) # # => 9 # # Returns the potency of the given numbers. def power(base, exponent) if exponent == 0 return 1 end i = 0 pot = 1 while i < exponent p pot pot *= base i += 1 end return pot end
require "forwardable" # This is a value object that represents a pair of engineers since there is no identity associated with # the combination of two engineers, the pair of those engineers should be equal to the pair of the same # engineers. # # See Pairing for how instances of pairs are stored. class Pair include Comparable extend Forwardable attr_reader :members def_delegators :@combined_id, :<=> def initialize(eng1, eng2) @members = [eng1, eng2] @combined_id = @members.map(&:id).map(&:to_s).sort.join("-") end def eql?(other) other == self end end
get '/signup/?' do erb :signup_form end post '/signup/?' do if /.+@.+\..+/i.match(params[:user][:email]).nil? flash[:danger] = 'The email address you entered seems to be invalid. Please try again.' redirect '/signup' elsif !User[email: params[:user][:email]].nil? flash[:info] = "The email address #{params[:user][:email]} already exists. Please log in with your previously registered password." redirect '/login' elsif params[:user][:password].empty? flash[:danger] = 'You need to enter a password. Please try again.' redirect '/signup' else user = User.new(params[:user]) if user.save session[:user_id] = user.id flash[:success] = 'You have signed up and everything is ready to go. Enjoy!' DB.transaction do SignupConfirmation.enqueue(user.email) end redirect '/user' else flash[:warning] = 'Your sign up did not succeed. Please try again.' redirect '/signup' end end end
class Gpsd < Formula desc "Global Positioning System (GPS) daemon" homepage "http://catb.org/gpsd/" url "https://download.savannah.gnu.org/releases/gpsd/gpsd-3.17.tar.gz" sha256 "68e0dbecfb5831997f8b3d6ba48aed812eb465d8c0089420ab68f9ce4d85e77a" bottle do cellar :any sha256 "89237ff11349f301e4a41a9f1d0ad7948f9a257d91a95be6ec6b4c9e26187f72" => :high_sierra sha256 "1a7912b32f3cc2d59d5d7b615ec3e8e2d14399d0256f2768b91be029f64e2438" => :sierra sha256 "6fb615b0aba85f6692cf6f8ac529ee8a2777d300bba6a9d8ff8abe90784d0fa5" => :el_capitan end depends_on "scons" => :build depends_on "libusb" => :optional def install scons "chrpath=False", "python=False", "strip=False", "prefix=#{prefix}/" scons "install" end end
require "rails_helper" RSpec.describe NewsLease, type: :model do context "associations" do it {is_expected.to belong_to(:user)} it {is_expected.to belong_to(:category)} it {is_expected.to belong_to(:place)} it {is_expected.to belong_to(:image)} end end
module GroupDocs class Signature # # Envelope and template entities share the same set of recipient methods. # # @see GroupDocs::Signature::Envelope # @see GroupDocs::Signature::Template # module RecipientMethods include Api::Helpers::SignaturePublic # # Returns recipients array. # # roles = GroupDocs::Signature::Role.get! # template = GroupDocs::Signature::Template.get!("g94h5g84hj9g4gf23i40j") # recipient = GroupDocs::Signature::Recipient.new # recipient.nickname = 'John Smith' # recipient.role_id = roles.detect { |role| role.name == "Signer" }.id # template.add_recipient! recipient # template.recipients! # # @param [Hash] options # @option options [Boolean] :public Defaults to false # @param [Hash] access Access credentials # @option access [String] :client_id # @option access [String] :private_key # @return [Array<GroupDocs::Signature::Recipient>] # def recipients!(options = {}, access = {}) json = Api::Request.new do |request| request[:access] = access request[:method] = :GET request[:path] = "/signature/#{client_id(options[:public])}/#{class_name.pluralize}/#{id}/recipients" end.execute! json[:recipients].map do |recipient| Signature::Recipient.new(recipient) end end # # Removes recipient. # # @example # template = GroupDocs::Signature::Template.get!("g94h5g84hj9g4gf23i40j") # recipient = template.recipients!.first # template.remove_recipient! recipient # # @example # envelope = GroupDocs::Signature::Envelope.get!("g94h5g84hj9g4gf23i40j") # recipient = envelope.recipients!.first # envelope.remove_recipient! recipient # # @param [GroupDocs::Signature::Recipient] recipient # @param [Hash] access Access credentials # @option access [String] :client_id # @option access [String] :private_key # @raise [ArgumentError] if recipient is not GroupDocs::Signature::Recipient # def remove_recipient!(recipient, access = {}) recipient.is_a?(GroupDocs::Signature::Recipient) or raise ArgumentError, "Recipient should be GroupDocs::Signature::Recipient object, received: #{recipient.inspect}" Api::Request.new do |request| request[:access] = access request[:method] = :DELETE request[:path] = "/signature/{{client_id}}/#{class_name.pluralize}/#{id}/recipients/#{recipient.id}" end.execute! end end # RecipientMethods end # Signature end # GroupDocs
class AddPriorityToSettings < ActiveRecord::Migration[5.2] def change add_column :settings, :priority, :integer add_column :maintenance_histories, :priority, :integer add_column :user_car_settings, :priority, :integer end end
class CreateGivs < ActiveRecord::Migration def change create_table :givs do |t| t.string 'title' t.string 'permalink' t.text 'description' t.string 'category' t.string 'subcategory' t.string 'tag' t.integer 'quantity', default:1 t.float 'cost' t.integer 'product_type' t.boolean 'visible',default:true #duration t.timestamps null: false end add_index :givs, "permalink" end end
# vim: ts=2 sts=2 et sw=2 ft=ruby fileencoding=utf-8 require "spec_helper" describe DMM::Response do before :all do stub_get.to_return(xml_response("com.xml")) @response = DMM::new.item_list end describe "Response" do subject { @response } it { should respond_to(:request) } it { should respond_to(:result) } its(:request) { should be_a(Hash) } its(:result) { should be_a(DMM::Response::Result) } end end describe DMM::Response::Result do before :each do stub_get.to_return(xml_response("com.xml")) @result = DMM::new.item_list.result end describe '#items' do context "items.size > 0" do subject { @result } its(:items) { should be_an(Array) } specify do subject.items.each do |item| item.should be_a(DMM::Response::Item) end end end context "items.size == 0" do before do stub_get.to_return(xml_response("zero_items.xml")) @result = DMM::new.item_list.result end subject { @result } its(:items) { should be_an(Array) } specify do subject.items.size.should == 0 end end end describe 'instance methods' do subject { @result } (DMM::Response::Result::RESULT_KEYS - [:items]).each do |key| it { should respond_to(key) } its(key) { should be_a(Integer) } end end end
class Messenger def self.send_message(number, message, from_number: ENV.fetch('PHONE_NUMBER'), logger: nil) account_sid = ENV.fetch("TWILIO_ACCOUNT_SID") auth_token = ENV.fetch("TWILIO_AUTH_TOKEN") client = Twilio::REST::Client.new(account_sid, auth_token) logger.info %("Sending message \"#{message}\" to #{number}") unless logger.nil? message = client.messages.create( body: message, to: number, from: from_number) end end
module RollbarAPI class Client module Items def get_item(item_id) get("/item/#{item_id}") end def item_by_counter(counter) get("/item_by_counter/#{counter}") end def all_items get('/items/') end def update_item(item_id, options = {}) patch("/item/#{item_id}", body: options) end end end end
class CreateHaircontrols < ActiveRecord::Migration def change create_table :haircontrols do |t| t.string "userid" t.float "capFitTemperature" t.float "coolDownTime" t.datetime "timedate" t.float "maxAlarmTemperature" t.float "minAlarmTemperature" t.float "postCoolTime" t.float "railVoltagePercent" t.float "setpointTemperature" t.timestamps end end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :tetsukyojins has_many :red_uruhuramaiters has_many :blue_uruhuramaiters has_many :dualhorns has_many :gurendels has_many :pyurobols has_many :varahs has_many :bombs has_many :grenades has_many :fungongos has_many :sorns has_many :antesantans has_many :vivres has_many :ramashtus has_many :ksarliks has_many :mushufshes has_many :needsheggs has_many :lalds has_many :vanips has_many :murhushes has_many :mahouts has_many :shreds has_many :harmas has_many :yellows has_many :whites has_many :reds has_many :golds has_many :blues has_many :darks has_many :blacks has_many :waters has_many :thunders has_many :snows has_many :flames has_many :ices has_many :darkps has_many :floateyes has_many :buells has_many :evileyes has_many :ahrimans has_many :deathfloats has_many :gandharvas has_many :airloges has_many :gulquimaseras has_many :killerbees has_many :bytebugs has_many :wasps has_many :neviros has_many :condors has_many :seamulgs has_many :arcuones has_many :dinonics has_many :ipils has_many :rapturs has_many :merusines has_many :schmerkes has_many :yowees has_many :zauras has_many :dingos has_many :michenfangs has_many :garms has_many :snowwolves has_many :sandwolves has_many :skols has_many :bandersnatches has_many :balsams has_many :galdas has_many :basilisks has_many :ochus has_many :unsabotenders has_many :larvas has_many :kushipos has_many :chimeras has_many :zoos has_many :sandworms has_many :sabotenders has_many :quals has_many :hedgevipers has_many :ogres has_many :morbols has_many :chimerabrains has_many :epages has_many :ghosts has_many :domperis has_many :glatts has_many :mandragoras has_many :behemoths has_many :splashers has_many :akeolos has_many :ragings has_many :ashuras has_many :wraiths has_many :devilmonoliths has_many :morbolgreats has_many :barbados has_many :adamantais has_many :kingbehemoths has_many :spirits has_many :metiers has_many :masterquals has_many :masterdomperis has_many :varnas end
module BaseballPress module Players extend self extend Download def stats(game_date) season = game_date.season games = game_date.games url = "http://www.baseballpress.com/lineups/%d-%02d-%02d" % [game_date.year, game_date.month, game_date.day] doc = download_file(url) css = ".players div, .team-name+ div, .team-name, .game-time" elements = doc.css(css) game_index = -1 away_lineup = home_lineup = false away_team = home_team = nil team_index = pitcher_index = batter_index = 0 away_teams = Set.new teams = Set.new pitchers = [] batters = [] elements.each_with_index do |element, index| type = element_type(element) case type when 'time' game_index += 1 batter_index = 0 away_teams << away_team if away_team next when 'lineup' if team_index%2 == 0 away_team = Team.find_by_name(element.text) away_lineup = true teams << away_team else home_team = Team.find_by_name(element.text) home_lineup = true teams << home_team end team_index += 1 next when 'no lineup' if team_index%2 == 0 away_team = Team.find_by_name(element.text) away_lineup = false teams << away_team else home_team = Team.find_by_name(element.text) home_lineup = false teams << home_team end team_index += 1 next when 'pitcher' if element.text == "TBD" pitcher_index += 1 next else identity, fangraph_id, name, handedness = pitcher_info(element) end team = find_team_from_pitcher_index(pitcher_index, away_team, home_team) pitcher_index += 1 when 'batter' identity, fangraph_id, name, handedness, lineup, position = batter_info(element) team = find_team_from_batter_index(batter_index, away_team, home_team, away_lineup, home_lineup) batter_index += 1 end player = Player.find_by(name: name, identity: identity, team: team) puts name # Make sure player is in database, otherwise create him if !player options = {} if type == 'pitcher' options[:throwhand] = handedness else options[:bathand] = handedness end options.merge!({season: season, team: team, name: name, identity: identity}) player = Player.create(options) puts "Player #{player.name} created" end game = find_game(games, away_team, away_teams) if type == 'pitcher' pitchers.push({statable: player, intervalable: game, starter: true}) elsif type == 'batter' batters.push({statable: player, intervalable: game, starter: true, position: position, lineup: lineup}) end end return {batters: batters, pitchers: pitchers, teams: teams} end def find_team_from_pitcher_index(pitcher_index, away_team, home_team) pitcher_index%2 == 0 ? away_team : home_team end def find_team_from_batter_index(batter_index, away_team, home_team, away_lineup, home_lineup) if away_lineup && home_lineup batter_index/9 == 0 ? away_team : home_team else away_lineup ? away_team : home_team end end def find_game(games, away_team, teams) games = games.where(away_team: away_team) size = games.size if size == 1 return games.first elsif size == 2 return teams.include?(away_team) ? games.second : games.first end end def element_type(element) element_class = element['class'] case element_class when /game-time/ type = 'time' when /no-lineup/ type = 'no lineup' when /team-name/ type = 'lineup' else type = element.children.size == 3 ? 'batter' : 'pitcher' end return type end def pitcher_info(element) name = element.child.text identity = element.child['data-bref'] fangraph_id = element.child['data-razz'].gsub!(/[^0-9]/, "") handedness = element.children[1].text[2] return identity, fangraph_id, name, handedness end def batter_info(element) name = element.children[1].text lineup = element.child.to_s[0].to_i handedness = element.children[2].to_s[2] position = element.children[2].to_s.match(/\w*$/).to_s identity = element.children[1]['data-bref'] fangraph_id = element.children[1]['data-razz'].gsub!(/[^0-9]/, "") return identity, fangraph_id, name, handedness, lineup, position end end end
class ID attr_accessor :id, :content def initialize(id,content) @id = id @content = content end #cette fonction nous renvoie un array d'objets comment avec tous les commentaires stockes dans le fichier csv def self.all id_array = [] #on initialise un array vide CSV.read("./db/ids.csv").each do |line| id_array << ID.new(line[0],line[1]) end return id_array end #cette fonction sauvegarde en mémoire le commentaire en question def save CSV.open("./db/ids.csv", "a") do |csv| csv << [@id,@content] end end def self.all_with_id (id) return self.all.select {|comment| comment.id.to_i == id} end end
#!/usr/bin/env ruby require 'sinatra' require 'fileutils' require 'rmagick' get '/:image' do |image| requested_file = "/Users/C453/Desktop/#{image}" if File.exists?(requested_file) puts "Recieved GET for #{requested_file}" content_type 'image/png' img = Magick::Image.read(requested_file)[0] img.format = 'png' img.to_blob else requested_file end end post '/Upload' do tempfile = params['file'][:tempfile] filename = Random_hash(8) + '.' + tempfile.readline().to_s.downcase; FileUtils.mv(tempfile.path, "filename.png") ("http://ss.C453.pw/" + filename).bytes end def Random_hash(length) characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" result = ''; 0.upto(length) { result += characters[rand(characters.length)]; } return result; end def Write_file (requested_file) file = File.read(requested_file) end
module Ricer::Plugins::Purple class Icq < Violet def protocol 'prpl-icq' end end end
# Polisher Core Ruby Extensions # # Licensed under the MIT license # Copyright (C) 2013 Red Hat, Inc. require 'polisher/rpmspec' class String def gem? File.extname(self) == ".gem" end def gemspec? File.extname(self) == ".gemspec" end def gemfile? File.basename(self) == "Gemfile" end def unrpmize fmm = Polisher::RPMSpec::FILE_MACRO_MATCHERS fmr = Polisher::RPMSpec::FILE_MACRO_REPLACEMENTS f = fmm.inject(self) { |file, matcher| file.gsub(matcher, '') } f = fmr.keys.inject(f) { |file, r| file.gsub(Regexp.new(r), fmr[r]) } f end def rpmize fmr = Polisher::RPMSpec::FILE_MACRO_REPLACEMENTS.invert fmr.keys.inject(self) { |file, r| file.gsub(r, fmr[r]) } end end
require 'minitest/autorun' require_relative 'test_helper' require_relative '../csv_parser' require_relative '../naive_bayes_trainer' require_relative '../naive_bayes_tester' class NaiveBayesTesterTest < MiniTest::Unit::TestCase def setup parsed_data1 = CSVParser.new('./test/test_data/test_transcripts_class1.csv').parse parsed_data2 = CSVParser.new('./test/test_data/test_transcripts_class2.csv').parse @trainer1 = NaiveBayesTrainer.new(primary_class_data: parsed_data1, other_class_data: parsed_data2) @test_data = ['simple', 'test'] end def test_can_compute_probability_of_being_a_class tester = NaiveBayesTester.new(trainer: @trainer1, test_data: @test_data) assert_equal 0.11538461538461539 * 0.038461538461538464 * 0.375, tester.probability_of_being_primary_class end end
actions :install, :upgrade, :remove default_action :install attribute :version, :kind_of => String attribute :source, :kind_of => String attribute :options, :kind_of => [String, Hash]
class AppointmentDrop < Liquid::Drop include ApplicationHelper include PhoneNumberHelper include AppointmentsHelper include SubscriptionsHelper include ActionView::Helpers::NumberHelper include ActionView::Helpers::TextHelper def initialize(appointment) @appointment = appointment end def start_time_approximate formatted_time(@appointment.start_time, :exact => false) end def start_time_approx_one "#{@appointment.start_time.strftime('%-l %p')} - #{(@appointment.start_time + 1.hour).strftime('%-l %p')}" end def start_time_approx_two "#{@appointment.start_time.strftime('%-l %p')} - #{(@appointment.start_time + 2.hours).strftime('%-l %p')}" end def start_time formatted_time(@appointment.start_time, :exact => true) end def am_pm @appointment.start_time.hour < 12 ? "morning" : "afternoon" end def end_time formatted_time(@appointment.end_time, :exact => true) end def start_date_in_words @appointment.start_time.strftime('%A, %b %-d') end def start_date @appointment.start_time.strftime('%-m/%-d/%Y') end def customer_phone_number formatted_phone_number @appointment.customer.phone_numbers.first.try(:phone_number) end def address address = @appointment.address "#{address.line1}, #{address.city}, #{address.state} #{address.postal_code}" end def address_alt address = @appointment.address "#{address.line1}<br> #{address.city}, #{address.state} #{address.postal_code}" end def assigned_cleaners "#{@appointment.team.present? ? "<i>#{@appointment.team.name}</i><br>" : ""}#{@appointment.employees.map { |e| e.full_name }.join("<br>")}" end def notes simple_format_no_tags(@appointment.notes) end def customer_notes simple_format_no_tags(@appointment.customer.notes) end def appointment_custom_fields # Note, the visible scope includes a join on the custom field @appointment.appointment_items.visible.order("custom_fields.order ASC").map { |item| "<b>#{item.custom_field.field_name}</b> #{item.value_name}" }.join("<br>") end def customer_custom_fields # Note, the visible scope includes a join on the custom field @appointment.customer.customer_items.visible.order("custom_fields.order ASC").map { |item| "<b>#{item.custom_field.field_name}</b> #{item.value_name}" }.join("<br>") end def customer_contact_emails @appointment.customer.emails.map { |email| email.address }.join('<br>') end def customer_contact_phone_numbers @appointment.customer.phone_numbers.map { |ph| "#{formatted_phone_number ph.phone_number} (#{ph.phone_number_type})"}.join("<br>") end def service_type @appointment.service_type.present? ? @appointment.service_type.name : "Cleaning" end def recurrence if @appointment.subscription.repeat "Repeats #{recurrence_in_words(@appointment.subscription)}" else "One Time Service" end end def balance number_to_currency(@appointment.price) end def paid yes_no(@appointment.paid?) end def instructions @appointment.appointment_service_items.joins(:instruction).order("instructions.order ASC").map { |service_item| "#{service_item.field_name} " + (service_item.value_name.present? ? "- #{service_item.value_name}" : "") }.join("<br>") end def contact_name @appointment.customer.contact_name.present? ? @appointment.customer.contact_name : @appointment.customer.company_name end def full_contact_name @appointment.customer.full_name end def company_name @appointment.user.user_profile.company_name end def company_email @appointment.user.user_profile.company_email end def company_phone_number formatted_phone_number @appointment.user.user_profile.company_phone_number end def hashed_customer_items if @hashed_customer_items.blank? custom_items = @appointment.customer.customer_items.includes(:custom_field) @hashed_customer_items = {} custom_items.each do |item| @hashed_customer_items[item.custom_field.field_name.downcase.tr(' ', '_')] = item.value_name end end return @hashed_customer_items end def hashed_appointment_items if @hashed_appointment_items.blank? custom_items = @appointment.appointment_items.includes(:appointment_field) @hashed_appointment_items = {} custom_items.each do |item| @hashed_appointment_items[item.appointment_field.field_name.downcase.tr(' ', '_')] = item.value_name end end @hashed_appointment_items end def logo "<img alt=\"Logo\" src=\"#{@appointment.user.user_profile.logo_url(:thumb)}\">" if @appointment.user.user_profile.logo.present? end def website if @appointment.user.user_profile.try(:website).present? "<a href=\"#{smart_add_url_protocol @appointment.user.user_profile.website}\">#{@appointment.user.user_profile.website}</a>" end end def facebook if @appointment.user.user_profile.try(:facebook_page).present? "<a href=\"#{smart_add_url_protocol @appointment.user.user_profile.facebook_page}\">Like us on Facebook!</a>" end end def status @appointment.status.try(:name) end def contact_first_name @appointment.customer.first_name end def contact_last_name @appointment.customer.last_name end def contact_company_name @appointment.customer.company_name end end
# -*- mode: ruby -*- # vi: set ft=ruby : ip_address = "10.1.1.20" public_ip_address = "" appname = "tavro" hostname = appname + ".dev" # ======================================================================== Vagrant.configure(2) do |config| # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. Vagrant.require_version ">= 1.9.0" # Set the name of the VM. See: http://stackoverflow.com/a/17864388/100134 config.vm.define appname required_plugins = %w(vagrant-vbguest vagrant-docker-compose vagrant-hostsupdater) plugins_to_install = required_plugins.select { |plugin| not Vagrant.has_plugin? plugin } if not plugins_to_install.empty? puts "Installing plugins: #{plugins_to_install.join(' ')}" if system "vagrant plugin install #{plugins_to_install.join(' ')}" exec "vagrant #{ARGV.join(' ')}" else abort "Installation of one or more plugins has failed. Aborting." end end config.vm.box = "ubuntu/xenial64" # Networking configuration. config.vm.hostname = hostname config.vm.network :private_network, ip: ip_address, auto_network: ip_address == '0.0.0.0' && Vagrant.has_plugin?('vagrant-auto_network') unless public_ip_address.empty? config.vm.network :public_network, ip: public_ip_address != '0.0.0.0' ? public_ip_address : nil end # If a hostsfile manager plugin is installed, add all server names as aliases. aliases = ["api." + hostname, "admin." + hostname, "www." + hostname, "app." + hostname, "db." + hostname] if Vagrant.has_plugin?('vagrant-hostsupdater') config.hostsupdater.aliases = aliases elsif Vagrant.has_plugin?('vagrant-hostmanager') config.hostmanager.enabled = true config.hostmanager.manage_host = true config.hostmanager.aliases = aliases end # from VVV # SSH Agent Forwarding # # Enable agent forwarding on vagrant ssh commands. This allows you to use ssh keys # on your host machine inside the guest. See the manual for `ssh-add`. config.ssh.forward_agent = true # Configuration options for the VirtualBox provider. config.vm.provider :virtualbox do |v| v.customize ["modifyvm", :id, "--memory", 1024] v.customize ["modifyvm", :id, "--cpus", 2] v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] v.customize ["modifyvm", :id, "--natdnsproxy1", "on"] v.customize ['modifyvm', :id, '--ioapic', 'on'] end # NFS is waaaaay faster than the standard rsync, and this way we determine the # root directory structure to replicate production as well. config.vm.synced_folder '.', "/tavro", :nfs => true compose_env = Hash.new if File.file?('.env') # read lines "var=value" into hash compose_env = Hash[*File.read('.env').split(/[=\n]+/)] # ignore keys (lines) starting with # compose_env.delete_if { |key, value| key.to_s.match(/^#.*/) } end config.vm.provision :docker config.vm.provision :docker_compose, project_name: appname, yml: "/tavro/docker-compose.yml", env: compose_env, rebuild: true, run: "always" config.vm.post_up_message = "aglio -i api/blueprint.apib -o api/docs/apib.html" config.vm.post_up_message = "Visit the official docs for setting up authentication keys: https://zoadilack.atlassian.net/wiki/pages/viewpage.action?pageId=1966120#Provisioning&DevOps-tavro-dev-env" config.vm.post_up_message = "TAVRO DEV ENVIRONMENT COMPLETE!" end
Rails.application.routes.draw do namespace :api, defaults: {format: :json} do resource :user, only: [:create] resource :session, only: [:create, :destroy] resources :businesses, only: [:index, :show, :create] resources :reviews, only: [:create, :show, :destroy] end root to: 'static_pages#root' end # Prefix Verb URI Pattern Controller#Action # api_user POST /api/user(.:format) api/users#create {:format=>:json} # api_session DELETE /api/session(.:format) api/sessions#destroy {:format=>:json} # POST /api/session(.:format) api/sessions#create {:format=>:json} # api_businesses GET /api/businesses(.:format) api/businesses#index {:format=>:json} # POST /api/businesses(.:format) api/businesses#create {:format=>:json} # api_business GET /api/businesses/:id(.:format) api/businesses#show {:format=>:json} # api_reviews POST /api/reviews(.:format) api/reviews#create {:format=>:json} # api_review GET /api/reviews/:id(.:format) api/reviews#show {:format=>:json} # root GET / static_pages#root # rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show # rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show # rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show # update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update # rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
#this seriously needs rewrite #later rails supports this already but our version does not class Object alias_method :try, :__send__ def tap yield self self end end class NilClass def try(*args) nil end end #our custom extensions class Hash def deep_delete_if_nil delete_if{|k,v| v.nil? } each do |k, v| if v.kind_of?(Hash) v.deep_delete_if_nil elsif v.respond_to?(:each) v.each do |item| v.deep_delete_if_nil if v.kind_of?(Hash) end end end end end module GL module Acts module ExtjsStore class FinderProxy alias_method :proxy_respond_to?, :respond_to? instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|proxy_|^object_id$|eval$)/ } attr_reader :find_args, :target, :find_options def initialize(klass) @target = klass end def find(*args) @find_args = args @find_options = @find_args.extract_options! @find_options.symbolize_keys! end def find_args @find_args.dup end def find_options @find_options.dup end def constraint_to_condition(field, condition, value = nil) @map ||= { :eq => '=', :ne => '!=', :like => 'like', :gt => '>', :gte => '>=', :lt => '<', :lte => '<=', :not_null => 'IS NOT NULL', :null => 'IS NULL' } value = [:null, :not_null].include?(condition.to_sym) ? '' : value warn "wrong condition #{condition}" unless @map[condition.to_sym] "`#{table_name}`.`#{field}` #{@map[condition.to_sym]} #{value}" end def constraints_to_conditions(constraints, separator = 'AND') array = [] constraints.each do |field, hash| next if hash.values.first.blank? array << constraint_to_condition(field, hash.keys.first, hash.values.first) end array.join(" #{separator} ") end def constraints_to_conditions_hash(constraints) raise "this thing is broken as of now, don't use hash in conditions atm!!" hash = {} constraints.each do |field, hash| next if hash.values.first.blank? hash[field.to_sym] = hash.values.first end hash end def derive_active_record_args_from_find_args options = find_options options = options.slice(:conditions, :order, :group, :having, :limit, :offset, :joins, :include, :select, :from, :readonly, :lock, :start, :sort, :constraints, :dir) #get some of the @target's sort mapping info maps = (@target.send(:extjs_store_options)[:sort_maps] || {}).symbolize_keys limit = options[:limit] offset = options.delete(:start) || (!!limit && 0) || nil column = options.delete(:sort) direction = options.delete(:dir) || (!column.blank? && 'ASC') || nil constraints = options.delete(:constraints) || {} options[:conditions] ||= ['true'] if options[:conditions].kind_of?(Hash) options[:conditions].update(constraints_to_conditions_hash(constraints)) elsif options[:conditions].kind_of?(Array) c = constraints_to_conditions(constraints) options[:conditions][0] << " AND #{c}" unless c.blank? end unless column.blank? column = maps[column.to_sym] || column column = column.split(',').map do |col| "`#{(col.strip).split('.').join('`.`')}`" end.join(',') end order = column.blank? ? nil : "#{column} #{direction}" find_args + [options.update({ :limit => limit, :offset => offset, :order => order }).deep_delete_if_nil] end def proxy_find @target.find(*derive_active_record_args_from_find_args) end def proxy_count options = find_options options = options.slice(:conditions, :joins, :include, :order, :distinct, :from) @target.count(options) end def send(method, *args) if proxy_respond_to?(method) super else @target.send(method, *args) end end private # Forwards any missing method call to the \target. def method_missing(method, *args) if block_given? @target.send(method, *args) { |*block_args| yield(*block_args) } else @target.send(method, *args) end end end def self.included(base) base.send(:extend, ClassMethods) end module ClassMethods # exclude - should be an array of string or symbol that are column names or methods # include - should be an array of string or symbol that are column names or methods # delegates - shoud be an array mix of hash, that has the form: # [ # {:prefix => true, :name => :attribute_or_method_name, :to => :association, :default => '1', :filter => lambda {|a| a.crazy? ? "hell yeah" : "nope"}}, #this will be called thru: model.association.other_value # {:prefix => :my_prefix, :name => :attribute_or_method_name, :to => :association, :default => '1', :filter => lambda {|a| a.crazy? ? "hell yeah" : "nope"}}, #this will be called thru: model.association.other_value # {:attribute_or_method_name => :association } # ] # use_meta - true to include the metadata of the records in the store # filters - hash proprocessor to attributes or methods: # { # :id => lambda{ |id| Math.square(id) }, #arity 1 # :name => :upcase, :user_name => :capitalize, # :other_name => lambda{ |full_name, record| record.name + full_name } #arity 2, # } def acts_as_extjs_store(*args) send(:extend, GL::Acts::ExtjsStore::SingletonMethods) options = args.extract_options! options ||= {} meta_options = options.delete(:use_meta) options = { :use_meta => true, :include => [], :exclude => [], :delegates => [], :filters => {} }.merge(options).symbolize_keys meta_options ||= {} write_inheritable_attribute :extjs_store_options, options.freeze class_inheritable_reader :extjs_store_options write_inheritable_attribute :extjs_store_meta, store_meta(meta_options) class_inheritable_reader :extjs_store_meta class_eval do attr_accessor :excerpt end end end module SingletonMethods def store_column_names(options = {}) options = extjs_store_options.merge(options) exclude = options[:exclude] includes = options[:include] (includes.empty? ? column_names : includes.map(&:to_s)).uniq - exclude.map(&:to_s) end def store_meta(options = {}) { :totalProperty => :total, :idProperty => :id, :root => table_name, :successProperty => :success }.merge(options) end def do_nothing lambda {|a| a} end def normalize_delegate(attributes) attributes.symbolize_keys! if (attributes.keys.size == 1) {:prefix => false, :name => attributes.keys.first, :to => attributes.values.first, :filter => do_nothing} else attributes.reverse_merge( :prefix => false, :filter => do_nothing ) end end def name_for_delegate(record, attributes) case attributes[:prefix] when true then attributes.values_at(:to, :name).join('_') when false,nil then record.respond_to?(attributes[:name]) ? attributes.values_at(:to, :name).join('_') : attributes[:name] else attributes.values_at(:prefix, :name).join('_') end end def value_for_delegate(record, attributes) potential = record.send(attributes[:to]).send(:try, attributes[:name]) potential ||= attributes[:default] if attributes.keys.include?(:default) potential = attributes[:filter].call(potential) if attributes[:filter] potential end def value_for_column(record, attribute, options) potential = record.send(:attributes)[attribute.to_s] || record.send(attribute) if(proc = options[:filters][attribute.to_sym]) proc = proc.to_sym.to_proc unless proc.kind_of?(Proc) proc end filter = (proc || do_nothing) args = [potential] args << record if filter.arity == 2 filter.call(*args) end #humanizing the field name might not be good def field_namer(name, strategy = :humanize) {:name => name , :mapping => name} end def adjust_to_active_record_options(store_options, params) model = name.constantize options = params.dup.symbolize_keys params.clear column = options.delete(:sort) direction = options.delete(:dir) if store_options[:sort_maps] and !column.blank? h = store_options[:sort_maps].symbolize_keys i = h.index(column.to_s) column = i || column end params.update(:sortInfo => {:field => column, :direction => direction}) Rails.logger.debug("sort info : %s" % params.inspect ) params.update(options.except(:conditions, :order, :group, :having, :limit, :offset, :joins, :include, :select, :from, :readonly, :lock, :start, :sort, :constraints, :dir)) params.deep_delete_if_nil params.delete(:sortInfo) if params[:sortInfo].blank? params end #options can have: #include - columns to include #exclude - columns to exclude #delegates - same delegate options as acts_as_extjs_store #use_meta - true or false to add metaData to the result #meta - override the metadata from acts_as_extjs_store #column_preprocessors - override the column_preprocessors from acts_as_extjs_store #constraints - dsl for constrainted store load(only applies to actual fields) # constraints['name'] = {:like => 1} # constraints['account_id'] = {:eq => 1} # valids are: 'eq', 'ne', 'gt', 'gte' def store(*args,&proc) klass = name.constantize options = args.extract_options! options = {} unless options.instance_of?(Hash) meta_option = options.delete(:meta) options = extjs_store_options.deep_merge(options).freeze meta = extjs_store_meta.deep_merge(meta_option || {}) scn = klass.store_column_names(options).freeze proxy = FinderProxy.new(klass) proxy.instance_eval(&proc) extra_meta = klass.adjust_to_active_record_options(options, proxy.find_options) meta = meta.deep_merge(extra_meta) proxy.proxy_find.instance_eval do delegates = options[:delegates].map do |attributes| klass.normalize_delegate(attributes) end array = [] each do |record, idx| attrib = {} scn.each do |method| attrib.update(method => klass.value_for_column(record, method, options)) end delegates.each do |delegate_attributes| attrib.update((name = klass.name_for_delegate(record, delegate_attributes)) => klass.value_for_delegate(record, delegate_attributes)) end array << attrib end result = { meta[:root] => array, meta[:totalProperty] => proxy.proxy_count, meta[:successProperty] => true} if options[:use_meta] n = klass.new meta[:fields] = scn.map{|method| klass.field_namer(method)} + delegates.map{|attributes|klass.field_namer(klass.name_for_delegate(n, attributes))} meta.symbolize_keys! meta.delete(:include) result[:metaData] = meta end result end end end end #ExtjsStore end #Acts end #GL ActiveRecord::Base.class_eval do include GL::Acts::ExtjsStore end