text
stringlengths
10
2.61M
# == Schema Information # # Table name: admins # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0) # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # created_at :datetime not null # updated_at :datetime not null # require 'spec_helper' describe Admin do it "should have a valid factory" do FactoryGirl.create(:admin).should be_valid end it { should respond_to(:email) } it { should respond_to(:post) } it { should respond_to(:encrypted_password) } it "must have proper email format" do FactoryGirl.build(:admin, email: "user@foo,com").should_not be_valid FactoryGirl.build(:admin, email: "user_at_foo.org").should_not be_valid FactoryGirl.build(:admin, email: "user is lame").should_not be_valid FactoryGirl.build(:admin, email: "testing@foo.").should_not be_valid FactoryGirl.build(:admin, email: "test.ing123@foobar.org").should be_valid end it "must reject duplicate emails" do FactoryGirl.create(:admin, email: "foo@bar.com") FactoryGirl.build(:admin, email: "foo@bar.com").should_not be_valid end it "must not accept duplicate upcase emails" do FactoryGirl.create(:admin, email: "TEST@TEST.com") FactoryGirl.build(:admin, email: "test@test.com").should_not be_valid end it "must have matching passwords" do FactoryGirl.build(:admin, password_confirmation: "foosbars").should_not be_valid end it "must have an email" do FactoryGirl.build(:admin, email: nil).should_not be_valid end it "must have a password" do FactoryGirl.build(:admin, password: nil, password_confirmation: nil).should_not be_valid end it "must have an encrypted email" do FactoryGirl.create(:admin).encrypted_password.should_not be_blank end end
class EventImportWorker include Shoryuken::Worker shoryuken_options queue: ->{ "#{ENV['RAILS_ENV']}_event" } def perform(data) klass = Kernel.const_get(data.fetch("type").chomp('s').capitalize) klass.import_record(data) end end
class MoviesController < ApplicationController before_action :set_movie, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, only: [:edit, :update, :destroy, :new, :create] before_action :check_correct_user, only: [:edit, :update, :destroy] def index if request.format.json? @result = MovieSearch.new(params, page, current_user.try(:id)).filter end respond_to do |format| format.html format.json { render json: index_response, status: :ok } end end def show end def new @movie = Movie.new end def edit end def create @movie = current_user.movies.build(movie_params) respond_to do |format| if @movie.save format.html { redirect_to @movie, notice: 'Movie was successfully created.' } format.json { render :show, status: :created, location: @movie } else format.html { render :new } format.json { render json: @movie.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @movie.update(movie_params) format.html { redirect_to @movie, notice: 'Movie was successfully updated.' } format.json { render :show, status: :ok, location: @movie } else format.html { render :edit } format.json { render json: @movie.errors, status: :unprocessable_entity } end end end def destroy if valid_jwt?(params[:jwt]) && @movie.destroy head :no_content else render json: "", status: :unprocessable_entity end end private def set_movie @movie = Movie.find(params[:id]) end def movie_params params.require(:movie).permit(:name, :text, category_ids: []) end def page params[:page] || 1 end def check_correct_user unless @movie.user_id == current_user.id respond_to do |format| format.html { redirect_to root_path, notice: 'Unauthorize access!' } format.json { render json: 'Unauthorize access!', status: :unprocessable_entity } end end end def index_response { movies: @result[:movies], page: page, total_pages: Movie.total_pages(@result[:count]), search: @result[:search], facet: @result[:facet] } end end
class CommentsController < ApplicationController before_action :find_comment, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:show, :index] before_action :authorize_owner, only: [:edit, :destroy, :update] def new @comment = Comment.new end def create @comment = Comment.new comment_params @comment.user = current_user @post = Post.find params[:post_id] @comment.post = @post respond_to do |format| if @comment.save format.html { redirect_to post_path(@comment), notice: "Answer created!" } format.js { render :create_success } # will llok for file in view called /create_success.js.erb else format.html { render "/posts/show" } format.js { render :create_failure } end end # if @comment.save # redirect_to post_path(@post), notice: "Commnet created!" # CommentsMailer.notify_post_owner(@comment).deliver_now # else # render "/posts/show" # end end def show end def index @comments = Comment.order("created_at DESC") end def edit end def update if @comment.update comment_params redirect_to post_path(@post) else render :edit end end def destroy post = Post.find params[:post_id] @comment.destroy redirect_to post_path(post), notice: "Comment deleted" end private def comment_params params.require(:comment).permit(:body) end def find_comment @comment = Comment.find params[:id] end def authenticate_user! redirect_to new_session_path, alert: "please sign in" unless user_signed_in? end def authorize_owner redirect_to post_path(@comment.post.id), alert: "access denied" unless can? :manage, @comment end end
require 'test/helper' class Admin::AssetsControllerTest < ActionController::TestCase def setup @request.session[:typus_user_id] = typus_users(:admin).id end def test_should_test_polymorphic_relationship_message post_ = posts(:published) get :new, { :back_to => "/admin/posts/#{post_.id}/edit", :resource => post_.class.name, :resource_id => post_.id } assert_select 'body div#flash' do assert_select 'p', "You're adding a new Asset to Post. Do you want to cancel it?" assert_select 'a', "Do you want to cancel it?" end end def test_should_create_a_polymorphic_relationship post_ = posts(:published) assert_difference('post_.assets.count') do post :create, { :back_to => "/admin/posts/edit/#{post_.id}", :resource => post_.class.name, :resource_id => post_.id } end assert_response :redirect assert_redirected_to '/admin/posts/edit/1#assets' assert_equal "Asset successfully assigned to Post.", flash[:success] end def test_should_render_edit_and_verify_message_on_polymorphic_relationship post_ = posts(:published) get :edit, { :id => assets(:first).id, :back_to => "/admin/posts/#{post_.id}/edit", :resource => post_.class.name, :resource_id => post_.id } assert_select 'body div#flash' do assert_select 'p', "You're updating a Asset for Post. Do you want to cancel it?" assert_select 'a', "Do you want to cancel it?" end end def test_should_return_to_back_to_url options = Typus::Configuration.options.merge(:index_after_save => true) Typus::Configuration.stubs(:options).returns(options) post_ = posts(:published) asset_ = assets(:first) post :update, { :back_to => "/admin/posts/#{post_.id}/edit", :resource => post_.class.name, :resource_id => post_.id, :id => asset_.id } assert_response :redirect assert_redirected_to '/admin/posts/1/edit#assets' assert_equal "Asset successfully updated.", flash[:success] end end
class Concurso < ActiveRecord::Base has_many :provas belongs_to :situacao belongs_to :orgao belongs_to :escolaridade validates_presence_of :nome, :message => "- deve ser informado" validates_presence_of :descricao, :message => "- deve ser informado" validates_presence_of :orgao, :message => "- deve ser informado" validates_presence_of :situacao, :message => "- deve ser informado" validates_presence_of :escolaridade, :message => "- deve ser informado" validates_presence_of :vagas, :message => "- deve ser informado" validates_presence_of :remuneracao, :message => "- deve ser informado" validates_presence_of :cargo, :message => "- deve ser informado" #validates_numeracality_of :remuneracao, :less_then_or_equal_to <=24, :message => "- O valor deve ser menor do que o digitado" #validates_numeracality_of :taxa_inscricao, :less_then_or_equal_to <=24, :message => "- O valor deve ser menor do que o digitado" #validates_numeracality_of :salario, :less_then_or_equal_to <=24, :message => "- O valor deve ser menor do que o digitado" end
class RemoveVenmoRecurrings < ActiveRecord::Migration[7.0] def change drop_table :venmo_recurrings end end
class Suggestion < ApplicationRecord belongs_to :user attr_accessor :username def attributes super.merge('username' => self.username) end end
# frozen_string_literal: true require 'stannum/rspec/match_errors' require 'support/contracts/request_contract' # @note Integration spec for Stannum::Contracts::IndifferentHashContract. RSpec.describe Spec::RequestContract do include Stannum::RSpec::Matchers subject(:contract) { described_class.new } describe '.new' do it { expect(described_class).to be_constructible.with(0).arguments } end describe '#match' do let(:status) { Array(contract.match(actual))[0] } let(:errors) { Array(contract.match(actual))[1].with_messages } describe 'with a non-hash object' do let(:actual) { nil } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is not a Hash', path: [], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with an empty hash' do let(:actual) { {} } let(:expected_errors) do [ { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE }, { data: { required: true, type: String }, message: 'is not a String', path: %i[username], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing string keys' do let(:actual) { { 'username' => 'Alan Bradley' } } let(:expected_errors) do [ { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing symbol keys' do let(:actual) { { username: 'Alan Bradley' } } let(:expected_errors) do [ { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing and extra string keys' do let(:actual) { { 'role' => 'admin', 'username' => 'Alan Bradley' } } let(:expected_errors) do [ { data: { value: actual['role'] }, message: 'has extra keys', path: %w[role], type: Stannum::Constraints::Hashes::ExtraKeys::TYPE }, { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing and extra symbol keys' do let(:actual) { { role: 'admin', username: 'Alan Bradley' } } let(:expected_errors) do [ { data: { value: actual[:role] }, message: 'has extra keys', path: %i[role], type: Stannum::Constraints::Hashes::ExtraKeys::TYPE }, { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with string keys and non-matching values' do let(:actual) do { 'password' => 12_345, 'username' => 67_890 } end let(:expected_errors) do [ { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE }, { data: { required: true, type: String }, message: 'is not a String', path: %i[username], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with symbol keys and non-matching values' do let(:actual) do { password: 12_345, username: 67_890 } end let(:expected_errors) do [ { data: { required: true, type: String }, message: 'is not a String', path: %i[password], type: Stannum::Constraints::Type::TYPE }, { data: { required: true, type: String }, message: 'is not a String', path: %i[username], type: Stannum::Constraints::Type::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a matching hash with string keys' do let(:actual) do { 'username' => 'Alan Bradley', 'password' => 'tronlives' } end it { expect(errors).to be == [] } it { expect(status).to be true } end describe 'with a matching hash with symbol keys' do let(:actual) do { username: 'Alan Bradley', password: 'tronlives' } end it { expect(errors).to be == [] } it { expect(status).to be true } end describe 'with a hash with extra string keys' do let(:actual) do { 'username' => 'Alan Bradley', 'password' => 'tronlives', 'role' => 'admin' } end let(:expected_errors) do [ { data: { value: actual['role'] }, message: 'has extra keys', path: %w[role], type: Stannum::Constraints::Hashes::ExtraKeys::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with extra symbol keys' do let(:actual) do { username: 'Alan Bradley', password: 'tronlives', role: 'admin' } end let(:expected_errors) do [ { data: { value: actual[:role] }, message: 'has extra keys', path: %i[role], type: Stannum::Constraints::Hashes::ExtraKeys::TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end end describe '#negated_match' do let(:status) { Array(contract.negated_match(actual))[0] } let(:errors) { Array(contract.negated_match(actual))[1].with_messages } describe 'with a non-hash object' do let(:actual) { nil } it { expect(errors).to be == [] } it { expect(status).to be true } end describe 'with an empty hash' do let(:actual) { {} } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing string keys' do let(:actual) { { 'username' => 'Alan Bradley' } } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing symbol keys' do let(:actual) { { username: 'Alan Bradley' } } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing and extra string keys' do let(:actual) { { 'role' => 'admin', 'username' => 'Alan Bradley' } } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with missing and extra symbol keys' do let(:actual) { { role: 'admin', username: 'Alan Bradley' } } let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with string keys and non-matching values' do let(:actual) do { 'password' => 12_345, 'username' => 67_890 } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with symbol keys and non-matching values' do let(:actual) do { password: 12_345, username: 67_890 } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a matching hash with string keys' do let(:actual) do { 'username' => 'Alan Bradley', 'password' => 'tronlives' } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[password], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a matching hash with symbol keys' do let(:actual) do { username: 'Alan Bradley', password: 'tronlives' } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: {}, message: 'does not have extra keys', path: %i[], type: Stannum::Constraints::Hashes::ExtraKeys::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[password], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with extra string keys' do let(:actual) do { 'username' => 'Alan Bradley', 'password' => 'tronlives', 'role' => 'admin' } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[password], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end describe 'with a hash with extra symbol keys' do let(:actual) do { username: 'Alan Bradley', password: 'tronlives', role: 'admin' } end let(:expected_errors) do [ { data: { allow_empty: true, required: true, type: Hash }, message: 'is a Hash', path: %i[], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[password], type: Stannum::Constraints::Type::NEGATED_TYPE }, { data: { required: true, type: String }, message: 'is a String', path: %i[username], type: Stannum::Constraints::Type::NEGATED_TYPE } ] end it { expect(errors).to match_errors(expected_errors) } it { expect(status).to be false } end end end
require './test_helper' require 'api_client' class ApiClientTest < Test::Unit::TestCase context "grab_data_and_save" do # knowing that our pre-cooked JSON data has 109 books setup do fakeweb_google_books_search_url('rails', 'computers', 0, 40, 'json_responses/search_results_0.json') fakeweb_google_books_search_url('rails', 'computers', 40, 40, 'json_responses/search_results_1.json') fakeweb_google_books_search_url('rails', 'computers', 80, 40, 'json_responses/search_results_2.json') end context "when it returns only books unknown to db" do setup do ApiClient.stubs(:key_unknown?).returns true end should "save them all and save a list of their ids, clear cached pages and sets last updated" do ApiClient.expects(:save_to_redis).times(109) Redis.any_instance.expects(:lpush).with('book_ids', regexp_matches(/book:/) ).times(109) Redis.any_instance.expects(:del).with "cached_page_ids" Redis.any_instance.expects(:set).with("app:last_updated", anything) ApiClient.grab_data_and_save end end context "when a book has changed its etag" do setup do ApiClient.stubs(:key_unknown?).returns false end should "save this book, clear cached pages and sets last updated" do ApiClient.expects(:etag_has_changed?).with('book:YLIBOsn66XEC', 'gEoOg6Y+BqQ').times(1).returns(true) ApiClient.expects(:etag_has_changed?).with(regexp_matches(/book:(?!YLIBOsn66XEC)/), anything).times(108).returns false ApiClient.expects(:save_to_redis).with('book_ids', anything, anything).times(1) Redis.any_instance.expects(:lpush).never Redis.any_instance.expects(:del).with "cached_page_ids" Redis.any_instance.expects(:set).with("app:last_updated", anything) ApiClient.grab_data_and_save end end end end
require 'rubygems' begin require 'pryx' rescue Exception => e # it would be cool but-:) end require 'fileutils' require 'rubygems' require 'test/unit' require 'tempfile' $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'linux/lxc' class LinuxLxcTest < Test::Unit::TestCase def setup @temp_dir = Dir.mktmpdir @lxc_config = File.join(@temp_dir, 'lxc.config') File.write(@lxc_config, <<SAMPLE) # Template used to create this container: /usr/share/lxc/templates/lxc-ubuntu # Parameters passed to the template: # For additional config options, please look at lxc.container.conf(5) # Common configuration lxc.include = #{@temp_dir}/ubuntu.common.conf # Container specific configuration lxc.rootfs = /var/lib/lxc/border-eth0/rootfs lxc.mount = /var/lib/lxc/border-eth0/fstab lxc.utsname = border-eth0 lxc.arch = amd64 # Network configuration lxc.network.type = veth lxc.network.flags = up lxc.network.link = lxcbr0 lxc.network.hwaddr = 00:16:3e:67:03:4a SAMPLE @lxc_ubuntu_common_conf = File.join(@temp_dir, 'ubuntu.common.conf') File.write(@lxc_ubuntu_common_conf, <<SAMPLE) # Default pivot location lxc.pivotdir = lxc_putold # Default mount entries lxc.mount.entry = proc proc proc nodev,noexec,nosuid 0 0 lxc.mount.entry = sysfs sys sysfs defaults 0 0 lxc.mount.entry = /sys/fs/fuse/connections sys/fs/fuse/connections none bind,optional 0 0 lxc.mount.entry = /sys/kernel/debug sys/kernel/debug none bind,optional 0 0 lxc.mount.entry = /sys/kernel/security sys/kernel/security none bind,optional 0 0 lxc.mount.entry = /sys/fs/pstore sys/fs/pstore none bind,optional 0 0 # Default console settings lxc.devttydir = lxc lxc.tty = 4 lxc.pts = 1024 # Default capabilities lxc.cap.drop = sys_module mac_admin mac_override sys_time # When using LXC with apparmor, the container will be confined by default. # If you wish for it to instead run unconfined, copy the following line # (uncommented) to the container's configuration file. #lxc.aa_profile = unconfined # To support container nesting on an Ubuntu host while retaining most of # apparmor's added security, use the following two lines instead. #lxc.aa_profile = lxc-container-default-with-nesting #lxc.mount.auto = cgroup:mixed # Uncomment the following line to autodetect squid-deb-proxy configuration on the # host and forward it to the guest at start time. #lxc.hook.pre-start = /usr/share/lxc/hooks/squid-deb-proxy-client # If you wish to allow mounting block filesystems, then use the following # line instead, and make sure to grant access to the block device and/or loop # devices below in lxc.cgroup.devices.allow. #lxc.aa_profile = lxc-container-default-with-mounting # Default cgroup limits lxc.cgroup.devices.deny = a ## Allow any mknod (but not using the node) lxc.cgroup.devices.allow = c *:* m lxc.cgroup.devices.allow = b *:* m ## /dev/null and zero lxc.cgroup.devices.allow = c 1:3 rwm lxc.cgroup.devices.allow = c 1:5 rwm ## consoles lxc.cgroup.devices.allow = c 5:0 rwm lxc.cgroup.devices.allow = c 5:1 rwm ## /dev/{,u}random lxc.cgroup.devices.allow = c 1:8 rwm lxc.cgroup.devices.allow = c 1:9 rwm ## /dev/pts/* lxc.cgroup.devices.allow = c 5:2 rwm lxc.cgroup.devices.allow = c 136:* rwm ## rtc lxc.cgroup.devices.allow = c 254:0 rm ## fuse lxc.cgroup.devices.allow = c 10:229 rwm ## tun lxc.cgroup.devices.allow = c 10:200 rwm ## full lxc.cgroup.devices.allow = c 1:7 rwm ## hpet lxc.cgroup.devices.allow = c 10:228 rwm ## kvm lxc.cgroup.devices.allow = c 10:232 rwm ## To use loop devices, copy the following line to the container's ## configuration file (uncommented). #lxc.cgroup.devices.allow = b 7:* rwm lxc.net.0.type = veth lxc.net.0.flags = up lxc.net.0.link = br-int lxc.net.0.hwaddr = 00:16:4e:80:72:ab lxc.net.0.name = br-int lxc.net.1.type = phys lxc.net.1.flags = up lxc.net.1.link = eth1 lxc.net.1.name = lte # Blacklist some syscalls which are not safe in privileged # containers lxc.seccomp = /usr/share/lxc/config/common.seccomp lxc.include = #{File.join(@temp_dir, 'empty.conf.d')} lxc.include = #{File.join(@temp_dir, 'common.conf.d')} SAMPLE FileUtils.mkdir_p File.join(@temp_dir, 'empty.conf.d') FileUtils.mkdir_p File.join(@temp_dir, 'common.conf.d') @lxc_common_conf_d_wildcard = File.join(@temp_dir, 'common.conf.d', 'wildcard.conf') File.write(@lxc_common_conf_d_wildcard, <<SAMPLE) lxc.wildcard.loaded = true lxc.hook.mount = /usr/share/lxcfs/lxc.mount.hook lxc.hook.post-stop = /usr/share/lxcfs/lxc.reboot.hook SAMPLE end def teardown FileUtils.remove_entry_secure @temp_dir end def test_reader lxc = Linux::Lxc.parse(@lxc_config) assert_equal lxc.get('lxc').length, 52 assert_equal lxc.get('lxc.network').length, 4 assert_equal lxc.get('lxc.network.hwaddr').length, 1 assert_equal lxc.get('lxc.network.murks'), nil assert_equal lxc.get('lxc.wildcard.loaded').values[0], 'true' assert_equal lxc.get('lxc.wildcard.loaded')[0].file, @lxc_common_conf_d_wildcard assert_equal lxc.get('lxc.wildcard.loaded')[0].line, 1 assert_equal lxc.get('lxc.cgroup.devices.allow').values[4], 'c 5:0 rwm' assert_equal lxc.get('lxc.cgroup.devices.allow')[4].file, @lxc_ubuntu_common_conf assert_equal lxc.get('lxc.cgroup.devices.allow')[4].line, 48 assert_equal lxc.get('lxc.network.hwaddr').values, ['00:16:3e:67:03:4a'] assert_equal lxc.get('lxc.network.hwaddr').first.file, @lxc_config assert_equal lxc.get('lxc.network.hwaddr').first.line, 18 end def test_from_scratch lxc = Linux::Lxc.file(File.join(@temp_dir, 'base.f')) lxc.add('# base meno') lxc.add('lxc.cgroup.devices.allow', 'meno') incl = Linux::Lxc.file(File.join(@temp_dir, 'incl.f.conf')) lxc.add('lxc.include', incl) incl.add('# include meno') incl.add('lxc.network.hwaddr', '00:16:3e:67:03:4a') empty_d = Linux::Lxc.directory(File.join(@temp_dir, 'scratch.empty.d')) lxc.add('lxc.include', empty_d) scratch_d = Linux::Lxc.directory(File.join(@temp_dir, 'scratch.d')) lxc.add('lxc.include', scratch_d) scratch_file = scratch_d.add_file(File.join(@temp_dir, 'scratch.d', 'file.conf')) scratch_file.add('# include scratch') scratch_file.add('lxc.scratch_file', 'it_is_scratch_file') lxc.write lxc_read = Linux::Lxc.parse(lxc.file) assert_equal lxc_read.get('#').length, 3 assert_equal lxc_read.get('lxc.cgroup.devices.allow').values, ['meno'] assert_equal lxc_read.get('lxc.cgroup.devices.allow').first.file, lxc.file assert_equal lxc_read.get('lxc.cgroup.devices.allow').first.line, 2 assert_equal lxc_read.get('lxc.network.hwaddr').values, ['00:16:3e:67:03:4a'] assert_equal lxc_read.get('lxc.network.hwaddr').first.file, incl.file assert_equal lxc_read.get('lxc.network.hwaddr').first.line, 2 assert_equal lxc_read.get('lxc.scratch_file').values, ['it_is_scratch_file'] assert_equal lxc_read.get('lxc.scratch_file').first.file, scratch_file.file assert_equal lxc_read.get('lxc.scratch_file').first.line, 2 assert_equal lxc_read.index.files.length, 3 end def test_comment lxc = Linux::Lxc.parse(@lxc_config) assert_equal lxc.get('#').length, 42 assert_equal lxc.get('lxc.cgroup.devices.allow').length, 16 lxc.get('lxc.cgroup.devices.allow')[0].comment! assert_equal lxc.get('lxc.cgroup.devices.allow').length, 15 assert_equal lxc.get('#').length, 43 lxc.get('lxc.network').comment! assert_equal lxc.get('#').length, 47 assert_equal lxc.get('#')[45].to_s, '# lxc.network.link = lxcbr0' assert_equal lxc.get('lxc.network'), nil lxc.index.files.values.each do |file| file.real_fname = ::File.join(::File.dirname(file.file), "-.#{::File.basename(file.file)}") end lxc.write l2 = Linux::Lxc.parse(::File.join(::File.dirname(@lxc_config), "-.#{::File.basename(@lxc_config)}")) assert_equal l2.lines.first.key, "#" assert_equal l2.lines.first.value, "# Template used to create this container: /usr/share/lxc/templates/lxc-ubuntu" lxc.index.files.values.each do |file| file.file = ::File.join(::File.dirname(file.file), "+.#{::File.basename(file.file)}") end lxc.write l3 = Linux::Lxc.parse(::File.join(::File.dirname(@lxc_config), "+.#{::File.basename(@lxc_config)}")) assert_equal l3.lines.first.key, "#" assert_equal l3.lines.first.value, "# Template used to create this container: /usr/share/lxc/templates/lxc-ubuntu" assert_equal ::File.basename(l3.index.files.values[1].file), "+.ubuntu.common.conf" assert_equal l3.index.files.values[1].lines.first.key, "#" assert_equal l3.index.files.values[1].lines.first.value, "# Default pivot location" end def test_real_fname lxc = Linux::Lxc.file(File.join(@temp_dir, 'real_name')) lxc.add('# base meno') lxc.add('lxc.cgroup.devices.allow', 'meno') lxc.write lxc.real_fname = File.join(@temp_dir, 'test_name') incl = Linux::Lxc.file(File.join(@temp_dir, 'test_incl')) incl.real_fname = File.join(@temp_dir, 'real_incl') lxc.add('lxc.include', incl) incl.add('# include meno') incl.add('lxc.network.hwaddr', '00:16:3e:67:03:4a') lxc.write assert_equal File.exist?(File.join(@temp_dir, 'test_name')), true assert_equal File.exist?(File.join(@temp_dir, 'real_name')), true assert_equal File.exist?(File.join(@temp_dir, 'real_incl')), true assert_equal File.exist?(File.join(@temp_dir, 'test_incl')), false # assert_raise do #Fails, no Exceptions are raised begin lxc = Linux::Lxc.parse(File.join(@temp_dir, 'test_name')) assert_equal 'Doof', 'Darf nie passieren' rescue Exception => e assert_equal e.instance_of?(Errno::ENOENT), true assert_equal File.basename(e.message), 'test_incl' end # end end def test_lines lxc = Linux::Lxc.parse(@lxc_config) cnt = 0 lxc.all_lines { |_line| cnt += 1 } assert_equal cnt, 109 end def test_files lxc = Linux::Lxc.parse(@lxc_config) files = lxc.index.files.keys assert_equal files[0], @lxc_config assert_equal files[1], @lxc_ubuntu_common_conf assert_equal files[2], @lxc_common_conf_d_wildcard assert_equal files.length, 3 end def test_write lxc = Linux::Lxc.parse(@lxc_config) inc_file = "#{lxc.get('lxc.cgroup.devices.allow').first.lxc.file}.new" lxc.get('lxc.cgroup.devices.allow').first.lxc.file = inc_file lxc.get('lxc.cgroup.devices.allow')[5].value = 'meno' assert_equal lxc.get('lxc.cgroup.devices.allow').values[5], 'meno' lxc.get('lxc.network.hwaddr').first.value = 'construqt' assert_equal lxc.get('lxc.network.hwaddr').values, ['construqt'] assert_equal lxc.get('lxc.network.hwaddr').find{|i| i.value == 'construqt'}.value, 'construqt' lxc.write lxc_read = Linux::Lxc.parse(lxc.file) assert_equal lxc_read.get('lxc.cgroup.devices.allow').values[5], 'meno' assert_equal lxc_read.get('lxc.cgroup.devices.allow')[5].file, inc_file assert_equal lxc_read.get('lxc.cgroup.devices.allow')[5].line, 49 assert_equal lxc_read.get('lxc.network.hwaddr').values, ['construqt'] assert_equal lxc_read.get('lxc.network.hwaddr').first.file, lxc.file assert_equal lxc_read.get('lxc.network.hwaddr').first.line, 18 end def test_numeric_prefix_order assert_equal Linux::Lxc.numeric_prefix_order(["100_a", "1_b", "34d"]), ["1_b","34d","100_a"] assert_equal Linux::Lxc.numeric_prefix_order(["1_c", "1_a", "1a"]), ["1_a","1_c","1a"] assert_equal Linux::Lxc.numeric_prefix_order(["000100_a", "000001_b", "034d"]), ["000001_b","034d","000100_a"] assert_equal Linux::Lxc.numeric_prefix_order(["foo","100_a", "000001_b", "bar", "34d"]), ["000001_b","34d","100_a","bar", "foo"] assert_equal Linux::Lxc.numeric_prefix_order(["foo","yyy", "bar"]), ["bar", "foo", "yyy"] end end
# -*- coding: utf-8 -*- =begin rdoc Transifexと連携するためのユーティリティ =end module Transifex extend self API_URL_PREFIX = 'https://www.transifex.com/api/2'.freeze SLUG_SIZE = 50 CONTENT_TYPE_MULTIPART_FORMDATA = 'multipart/form-data' CONTENT_TYPE_APPLICATION_JSON = 'application/json' # Transifexプロジェクトの情報を取得する # ==== Args # [project_name] String プロジェクト名 # ==== Return # Hashプロジェクトの情報 def project_detail(project_name) get_request("/project/#{project_name}/?details") end # resource(mikutterの場合はpotファイル)をアップロードし、新しいResourceとして登録する。 # 既に同じslugを持つResourceは登録できない。代わりに、 Transifex.resource_update を使う # ==== Args # [project_name:] プロジェクト名 # [slug:] String アップロードするresourceのslug。プラグインスラッグを使用する。50文字まで # [name:] String resourceの名前。プラグイン名を使用する。 # [i18n_type:] String 翻訳形式。省略するとPO。mikutterでは必ず省略する。 # [categories:] Array カテゴリ。いらん # [priority:] Transifex::Priority 翻訳優先順位。 # [content:] IO|String resourceの内容。potファイルの中身のこと。IOを渡すとそれをreadした結果、Stringならその内容をそのままアップロードする # ==== Return # Hash レスポンス # ==== See # http://docs.transifex.com/api/resources/#uploading-and-downloading-resources # ==== Raise # SlugTooLongError slugが SLUG_SIZE 文字を超えている場合 def resource_create(project_name:, slug:, name:, i18n_type: 'PO', categories: [], priority: Priority::NORMAL, content:) slug, name, priority = slug.to_s, name.to_s, priority.to_i raise SlugTooLongError, "The current maximum value for the field slug is #{SLUG_SIZE} characters. http://docs.transifex.com/api/resources/#uploading-and-downloading-resources" if slug.size > SLUG_SIZE if content.is_a? IO content = content.read end post_request("/project/#{project_name}/resources/", content_type: CONTENT_TYPE_APPLICATION_JSON, params: { slug: slug, name: name, i18n_type: i18n_type, categories: categories, priority: priority, content: content } ) end # resource(mikutterの場合はpotファイル)をアップロードし、同じslugを持つResourceを上書きする。 # 存在しないResourceは登録できない。代わりに、 Transifex.resource_create を使う # ==== Args # [project_name:] プロジェクト名 # [slug:] String アップロードするresourceのslug。プラグインスラッグを使用する。50文字まで # [content:] IO|String resourceの内容。potファイルの中身のこと。IOを渡すとそれをreadした結果、Stringならその内容をそのままアップロードする # ==== Return # Hash レスポンス # ==== See # http://docs.transifex.com/api/resources/#uploading-and-downloading-translations-for-a-file def resource_update(project_name:, slug:, content:) slug = slug.to_s if content.is_a? IO content = content.read end put_request("/project/#{project_name}/resource/#{slug}/content/", content_type: CONTENT_TYPE_APPLICATION_JSON, params: {content: content} ) end def resource_get(project_name:, slug:) slug = slug.to_s get_request("/project/#{project_name}/resource/#{slug}/content/") end private def get_request(path) clnt = HTTPClient.new clnt.set_auth(API_URL_PREFIX, ENV['TRANSIFEX_USER'], ENV['TRANSIFEX_PASSWORD']) JSON.parse(clnt.get_content(API_URL_PREFIX + path), symbolize_names: true) end def post_request(path, content_type: CONTENT_TYPE_MULTIPART_FORMDATA, params:) clnt = HTTPClient.new clnt.set_auth(API_URL_PREFIX, ENV['TRANSIFEX_USER'], ENV['TRANSIFEX_PASSWORD']) case content_type when CONTENT_TYPE_MULTIPART_FORMDATA content = params when CONTENT_TYPE_APPLICATION_JSON content = params.to_json end JSON.parse(clnt.post_content(API_URL_PREFIX + path, content, 'Content-Type' => content_type), symbolize_names: true) rescue HTTPClient::BadResponseError => err pp err.res.content end def put_request(path, content_type: CONTENT_TYPE_MULTIPART_FORMDATA, params:) clnt = HTTPClient.new clnt.set_auth(API_URL_PREFIX, ENV['TRANSIFEX_USER'], ENV['TRANSIFEX_PASSWORD']) case content_type when CONTENT_TYPE_MULTIPART_FORMDATA content = params when CONTENT_TYPE_APPLICATION_JSON content = params.to_json end JSON.parse(clnt.__send__(:follow_redirect, :put, API_URL_PREFIX + path, nil, content, 'Content-Type' => content_type).content, symbolize_names: true) rescue HTTPClient::BadResponseError => err pp err.res.content end class Priority attr_reader :to_i def initialize(prio) @to_i = prio.to_i end NORMAL = new(0) HIGH = new(1) URGENT = new(2) end class Error < RuntimeError; end class SlugTooLongError < Error; end end
require 'rails_helper' RSpec.describe Category do subject { build :category } it { should belong_to(:vertical) } it { should have_many(:courses) } it { should validate_presence_of(:name) } it { should validate_uniqueness_of(:name) } it { should validate_presence_of(:state) } it 'validates uniqueness of name across Vertical and Category models' do create :vertical, name: 'TEST' category = build :category, name: 'TEST' expect(category).not_to be_valid end end
class LandsController < ApplicationController before_action :find_land, only: [:show, :edit, :update, :destroy] def index @lands = Land.all @plants = Plant.all end def show @diaries = @land.diaries @plants = @land.plants end def new @land = Land.new end def edit end def create @land = Land.new(land_params) @land.save redirect_to @land end def update @land.update(land_params) redirect_to @land end def destroy @land.destroy redirect_to action: 'index' end private def find_land @land = Land.find(params[:id]) end def land_params params.require(:land).permit( {plant_ids:[]}, :temperature, :name) 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) owner_1 = Owner.create(name: "John Smith", phone_number: 5555555555, email_address: "johnsmith@gmail.com", physical_address: "233 Belmont Avenue, Philadelphia, Pennsylvania 77777") owner_2 = Owner.create(name: "Priscilla Li", phone_number: 4444444444, email_address: "pli@hotmail.com", physical_address: "555 Rose Street, New York City, New York 88888") shelter_1 = Shelter.create(name: "New England Animal Shelter", physical_address: "333 Pennsylvania Lane, Boston, Massachusetts 99999") shelter_2 = Shelter.create(name: "Northeastern Animal Shelter", physical_address: "444 Belvedere Street, Providence, Rhode Island 55555") Dog.create(name: "Max", age: 4, breed: "Schnauzer", traits: "intelligent", weight: 16, shelter: shelter_1) Dog.create(name: "Mickey", age: 8, breed: "Cocker Spaniel", traits: "trustworthy", weight: 30, shelter: shelter_1) Dog.create(name: "Bella", age: 2, breed: "Labrador Retriever", traits: "sociable", weight: 60, shelter: shelter_1) Dog.create(name: "Sophie", age: 5, breed: "Beagle", traits: "playful", weight: 21, shelter: shelter_1) Dog.create(name: "Duke", age: 3, breed: "Maltese", traits: "affectionate", weight: 8, shelter: shelter_1) User.create(name: "Mary Zimmer", email: "maryzimmer@gmail.com", password: "ilovedogs", admin: false) User.create(name: "John Smith", email: "johnsmith@gmail.com", password: "dogsarethebest", admin: false) User.create(name: "Laura Rodriguez", email: "laurarodriguez@gmail.com", password: "dogsaremyfavorite", admin: true) User.create(name: "Anthony Brown", email: "anthonybrown@gmail.com", password: "myfavoritepetisadog", admin: true) User.create(name: "Priscilla Li", email: "priscillali@gmail.com", password: "myfirstpetwasadog", admin: false)
Rails.application.routes.draw do root "posts#index" get "/posts", to: "posts#index", as: :posts get "/posts/new", to: "posts#new", as: :new_post get "/posts/:id", to: "posts#show", as: :post post "/posts", to: "posts#create" get "/posts/:id/vote/:type", to: "posts#vote", as: :vote get "/posts/:id/:action", to: "posts#edit", as: :edit_post patch "/posts/:id", to: "posts#update" end
# frozen_string_literal: true Rails.application.routes.draw do # Use to user session -------------------- devise_for :users # Use to path app ------------------------ devise_scope :user do authenticated :user do root 'home#index', as: :authenticated_root end unauthenticated do root 'home#index', as: :unauthenticated_root end end # Main Routes root to: 'home#index' # Home Routes match 'home', to: 'home#index', via: :get, as: :home match 'home/about', to: 'home#about', via: :get, as: :about # Resources resources :brands resources :newsletters resources :news, only: :index resources :leeds, only: %i[index create] resources :purchases, only: %i[index show] resources :customers, only: %i[index show], param: :uid resources :contacts, only: %i[index new create show destroy] resources :suggestions, except: :update do resources :reply_suggestions, only: :create end resources :users, only: %i[index show destroy] do resources :quotes, only: %i[index new create] resources :orders, only: %i[create destroy show update] resources :pets end end
module ActiveStorageHelpers module_function def create_analyzed_file_blob(*args) create_file_blob(*args).tap(&:analyze) end def create_file_blob(filename: "ruby.jpg", content_type: "image/jpeg", metadata: nil) pathname = Pathname.new(Rails.root.to_s + "/spec/fixtures/files/#{filename}") ActiveStorage::Blob.create_after_upload!( io: pathname.open, filename: filename, content_type: content_type, metadata: metadata ) end def create_audio_blob create_blob(filename: "audio.wav", content_type: "audio/wav") end def create_blob(data: "Hello!", filename: "hello.txt", content_type: "text/plain") ActiveStorage::Blob.create_after_upload!( io: StringIO.new(data), filename: filename, content_type: content_type ) end end
require 'rails_helper' RSpec.describe "victims/new", type: :view do before(:each) do assign(:victim, Victim.new( incident: nil, name: "MyString", contact: "MyString", remark: "MyText", role: "MyString", employee: false, address: "MyString", email: "MyString", supervisor: "MyString" )) end it "renders new victim form" do render assert_select "form[action=?][method=?]", victims_path, "post" do assert_select "input[name=?]", "victim[incident_id]" assert_select "input[name=?]", "victim[name]" assert_select "input[name=?]", "victim[contact]" assert_select "textarea[name=?]", "victim[remark]" assert_select "input[name=?]", "victim[role]" assert_select "input[name=?]", "victim[employee]" assert_select "input[name=?]", "victim[address]" assert_select "input[name=?]", "victim[email]" assert_select "input[name=?]", "victim[supervisor]" end end end
class ICMPUnreach < ICMP attr_reader :icmp_pmvoid attr_reader :icmp_nextmtu def initialize(packet) super(packet) contents = packet.unpack('C4n2') @icmp_pmvoid = contents[4] @icmp_nextmtu = contents[5] end end
require 'bundler' require 'logger' require 'pathname' require 'rake' require 'rake/packagetask' require 'rubygems/installer' module Killbill class PluginHelper include Rake::DSL class << self def install_tasks(opts = {}) new(opts[:base_name] || Dir.pwd, # Path to the plugin root directory (where the gempec and/or Gemfile should be) opts[:plugin_name], # Plugin name, e.g. 'klogger' opts[:gem_name], # Gem file name, e.g. 'klogger-1.0.0.gem' opts[:gemfile_name] || "Gemfile", # Gemfile name opts[:gemfile_lock_name] || "Gemfile.lock", # Gemfile.lock name opts[:verbose] || false) .install end end def initialize(base_name, plugin_name, gem_name, gemfile_name, gemfile_lock_name, verbose) @verbose = verbose @logger = Logger.new(STDOUT) @logger.level = @verbose ? Logger::DEBUG : Logger::INFO @base_name = base_name @plugin_name = plugin_name @gem_name = gem_name @gemfile_name = gemfile_name @gemfile_lock_name = gemfile_lock_name # Plugin base directory @base = Pathname.new(@base_name).expand_path # Find the gemspec to determine name and version @plugin_gemspec = find_plugin_gemspec # Temporary build directory # Don't use 'pkg' as it is used by Rake::PackageTask already: it will # hard link all files from @package_dir to pkg to avoid tar'ing up symbolic links @package_dir = Pathname.new(name).expand_path # Staging area to install gem dependencies # Note the Killbill friendly structure (which we will keep in the tarball) @target_dir = @package_dir.join("#{version}/gems").expand_path # Staging area to install the killbill.properties and config.ru files @plugin_root_target_dir = @package_dir.join("#{version}").expand_path end def specs # Rely on the Gemfile definition, if it exists, to get all dependencies # (we assume the Gemfile includes the plugin gemspec, as it should). # Otherwise, use only the plugin gemspec. # When using the Gemfile definition, don't include the :development group -- should this be configurable? @specs ||= @gemfile_definition ? @gemfile_definition.specs_for([:default]) : [@plugin_gemspec] end def install namespace :killbill do desc "Validate plugin tree" # The killbill.properties file is required, but not the config.ru one task :validate, [:verbose] => killbill_properties_file do |t, args| set_verbosity(args) validate end # Build the .tar.gz and .zip packages task :package, [:verbose] => :stage package_task = Rake::PackageTask.new(name, version) do |p| p.need_tar_gz = true p.need_zip = true end desc "Stage all dependencies" task :stage, [:verbose] => :validate do |t, args| set_verbosity(args) stage_dependencies stage_extra_files # Small hack! Update the list of files to package (Rake::FileList is evaluated too early above) package_task.package_files = Rake::FileList.new("#{@package_dir.basename}/**/*") end desc "Deploy the plugin to Kill Bill" task :deploy, [:force, :plugin_dir, :verbose] => :stage do |t, args| set_verbosity(args) plugins_dir = Pathname.new("#{args.plugin_dir || '/var/tmp/bundles/plugins/ruby'}").expand_path mkdir_p plugins_dir, :verbose => @verbose plugin_path = Pathname.new("#{plugins_dir}/#{name}") if plugin_path.exist? if args.force == "true" @logger.info "Deleting previous plugin deployment #{plugin_path}" rm_rf plugin_path, :verbose => @verbose else raise "Cowardly not deleting previous plugin deployment #{plugin_path} - override with rake killbill:deploy[true]" end end cp_r @package_dir, plugins_dir, :verbose => @verbose Rake::FileList.new("#{@base}/*.yml").each do |config_file| config_file_path = Pathname.new("#{plugin_path}/#{version}/#{File.basename(config_file)}").expand_path @logger.info "Deploying #{config_file} to #{config_file_path}" cp config_file, config_file_path, :verbose => @verbose end end desc "List all dependencies" task :dependency => :validate do print_dependencies end desc "Delete #{@package_dir}" task :clean => :clobber_package do rm_rf @package_dir end end end private def set_verbosity(args) return unless args.verbose == 'true' @verbose = true @logger.level = Logger::DEBUG end def validate @gemfile_definition = find_gemfile end def print_dependencies puts "Gems to be staged:" specs.each { |spec| puts " #{spec.name} (#{spec.version})" } end def name @plugin_gemspec.name end def version @plugin_gemspec.version end # Parse the <plugin_name>.gemspec file def find_plugin_gemspec gemspecs = @plugin_name ? [File.join(@base, "#{@plugin_name}.gemspec")] : Dir[File.join(@base, "{,*}.gemspec")] raise "Unable to find your plugin gemspec in #{@base}" unless gemspecs.size == 1 spec_path = gemspecs.first @logger.debug "Parsing #{spec_path}" Bundler.load_gemspec(spec_path) end def find_plugin_gem(spec) gem_name = spec.file_name # spec.loaded_from is the path to the gemspec file base = Pathname.new(File.dirname(spec.loaded_from)).expand_path # Try in the base directory first plugin_gem_file = Pathname.new(gem_name).expand_path plugin_gem_file = base.join(gem_name).expand_path unless plugin_gem_file.file? # Try in subdirectories next unless plugin_gem_file.file? plugin_gem_files = Dir[File.join(base, "**/#{spec.file_name}")] @logger.debug "Gem candidates found: #{plugin_gem_files}" # Take the first one, assume the other ones are from build directories (e.g. pkg) plugin_gem_file = Pathname.new(plugin_gem_files.first).expand_path unless plugin_gem_files.empty? end raise "Unable to find #{gem_name} in #{base}. Did you build it? (`rake build')" unless plugin_gem_file.file? @logger.debug "Found #{plugin_gem_file}" Pathname.new(plugin_gem_file).expand_path end # Parse the existing Gemfile and Gemfile.lock files def find_gemfile gemfile = @base.join(@gemfile_name).expand_path # Don't make the Gemfile a requirement, a gemspec should be enough return nil unless gemfile.file? # Make sure the developer ran `bundle install' first. We could probably run # Bundler::Installer::install(@target_dir, @definition, {}) # but it may be better to make sure all dependencies are resolved first, # before attempting to build the plugin gemfile_lock = @base.join(@gemfile_lock_name).expand_path raise "Unable to find the Gemfile.lock at #{gemfile_lock} for your plugin. Please run `bundle install' first" unless gemfile_lock.file? @logger.debug "Parsing #{gemfile} and #{gemfile_lock}" Bundler::Definition.build(gemfile, gemfile_lock, nil) end def stage_dependencies # Create the target directory mkdir_p @target_dir.to_s, :verbose => @verbose @logger.debug "Installing all gem dependencies to #{@target_dir}" # We can't simply use Bundler::Installer unfortunately, because we can't tell it to copy the gems for cached ones # (it will default to using Bundler::Source::Path references to the gemspecs on "install"). specs.each do |spec| plugin_gem_file = Pathname.new(spec.cache_file).expand_path if plugin_gem_file.file? @logger.debug "Staging #{spec.name} (#{spec.version}) from #{plugin_gem_file}" else plugin_gem_file = find_plugin_gem(spec) @logger.info "Staging custom gem #{spec.full_name} from #{plugin_gem_file}" end do_install_gem(plugin_gem_file, spec.name, spec.version) end end def do_install_gem(path, name, version) gem_installer = Gem::Installer.new(path.to_s, { :force => true, :install_dir => @target_dir, # Should be redundant with the tweaks below :development => false, :wrappers => true }) # Tweak the spec file as there are a lot of things we don't care about gem_installer.spec.executables = nil gem_installer.spec.extensions = nil gem_installer.spec.extra_rdoc_files = nil gem_installer.spec.test_files = nil gem_installer.install rescue => e @logger.warn "Unable to stage #{name} (#{version}) from #{path}: #{e}" raise e end def stage_extra_files unless killbill_properties_file.nil? @logger.debug "Staging #{killbill_properties_file} to #{@plugin_root_target_dir}" cp killbill_properties_file, @plugin_root_target_dir, :verbose => @verbose end unless config_ru_file.nil? @logger.debug "Staging #{config_ru_file} to #{@plugin_root_target_dir}" cp config_ru_file, @plugin_root_target_dir, :verbose => @verbose end end def killbill_properties_file path_to_string @base.join("killbill.properties").expand_path end def config_ru_file path_to_string @base.join("config.ru").expand_path end def path_to_string(path) path.file? ? path.to_s : nil end end end
class CollisionComponent def initialize(parent, detector) raise 'Cannot create collision component when parent is nil' unless parent raise 'Cannot create collision component when detector is nil' unless detector @parent = parent @detector = detector end def id :collision end def free?(x, y) @detector.free?(x, y) end end
require 'osx/cocoa' module Installd class Preferences include OSX attr_accessor :username attr_accessor :itunes_directory attr_accessor :last_sync_status attr_accessor :launched_before attr_accessor :status_bar_enabled def initialize(bundle_identifier) @bundle_identifier = bundle_identifier load end def load @username = get_value('username', '').to_s @itunes_directory = get_value('itunes_directory', File.join(ENV['HOME'], 'Music', 'iTunes')).to_s @last_sync_status = get_value('last_sync_status', 'Not yet synced').to_s @launched_before = get_boolean_value('launched_before', false) @status_bar_enabled = get_boolean_value('status_bar_enabled', true) end def save set_value('username', @username) set_value('itunes_directory', @itunes_directory) set_value('last_sync_status', @last_sync_status) set_boolean_value('launched_before', @launched_before) set_boolean_value('status_bar_enabled', @status_bar_enabled) synchronize end private def get_value(key, default) CFPreferencesCopyAppValue(key, @bundle_identifier) || default end def get_boolean_value(key, default) value = CFPreferencesCopyAppValue(key, @bundle_identifier) value ? value.boolValue : default end def set_boolean_value(key, value) set_value(key, NSNumber.numberWithBool(value)) end def set_value(key, value) CFPreferencesSetAppValue(key, value, @bundle_identifier) end def synchronize if CFPreferencesAppSynchronize(@bundle_identifier) NSLog("Preferences#synchronize succeeded for #{@bundle_identifier}") else NSLog("Preferences#synchronize failed for #{@bundle_identifier}") end end end end
require 'spec_helper' property['dokku_plugins'].each do |item| describe command("dokku plugin | grep #{item['name']}") do its(:stdout) { should match /#{item['name']}\s+[0-9\.]+\s+enabled/ } its(:exit_status) { should eq 0 } end end
execute "pip3 install -U ." do cwd File.join(File.dirname(__FILE__), '..', '..', '..') environment({'LC_ALL' => "C.UTF-8"}) # ...for correct encoding in python open() end
require 'rails_helper' RSpec.describe Page, :type => :model do it "has a valid factory" do expect(build(:page)).to be_valid end end
#!/usr/bin/env ruby require 'thor' require_relative "preso_ro" class PresoRoRunner < Thor desc "generate PATH", "The path to the presentation config" def generate(path, prefix=nil) pres_prefix = prefix == nil ? path.delete("/") : prefix PresoGo.generate(path, pres_prefix) end def self.exit_on_failure? true end end PresoRoRunner.start(ARGV)
class AddColumnIgvToCostCenters < ActiveRecord::Migration def change add_column :cost_centers, :igv, :float end end
class ApiResourceUsers < ActionDispatch::IntegrationTest test 'GET users returns array of user objects' do get '/users', {}, {'Accept' => Mime::JSON} assert_equal 200, response.status json_body = body_to_json(response.body) assert_equal Mime::JSON, response.content_type end test 'POST users creates new user' do post '/users', { user: users(:joe) }.to_json, {'Accept' => Mime::JSON} assert_equal 201, response.status json_body = body_to_json(response.body) end test 'POST users multiple times causes error' do post '/users', { user: users(:joe) }.to_json, {'Accept' => Mime::JSON} post '/users', { user: users(:joe) }.to_json, {'Accept' => Mime::JSON} assert_not_equal 201, response.status end end
require_relative 'test_helper' class ItemRepositoryTest < Minitest::Test attr_reader :item_repo, :sales_engine, :data def setup @data = "test/fixtures/items_fixtures.csv" @item_repo = ItemRepository.new("test/fixtures/items_fixtures.csv", self) @sales_engine = SalesEngine.new end def test_it_exists assert item_repo end def test_the_file_to_read_exists assert File.exist?(item_repo.file) end def test_it_returns_all_instances assert_equal 100, item_repo.all.count end def test_it_returns_a_random_instance @test = [] 100.times { @test << @item_repo.random } @test = @test.uniq assert @test.count > 1 end def test_it_returns_a_find_by_id_match assert_equal "1", item_repo.find_by_id("1").id end def test_it_returns_a_find_by_name_match assert_equal "Item Qui Esse", item_repo.find_by_name("Item Qui Esse").name end def test_it_returns_a_find_by_name_lowercase_match assert_equal "Item Qui Esse", item_repo.find_by_name("item qui esse").name end def test_it_returns_a_find_by_description_match assert_equal "Nihil autem sit odio inventore deleniti. Est laudantium ratione distinctio laborum. Minus voluptatem nesciunt assumenda dicta voluptatum porro.", item_repo.find_by_description("Nihil autem sit odio inventore deleniti. Est laudantium ratione distinctio laborum. Minus voluptatem nesciunt assumenda dicta voluptatum porro.").description end def test_it_returns_a_find_by_unit_price_match assert_equal "75107", item_repo.find_by_unit_price("75107").unit_price end def test_it_returns_a_find_by_merchant_id_match assert_equal "1", item_repo.find_by_merchant_id("1").merchant_id end def test_it_returns_a_find_by_created_at_match assert_equal "2012-03-27 14:53:59 UTC", item_repo.find_by_created_at("2012-03-27 14:53:59 UTC").created_at end def test_it_returns_a_find_by_updated_at_match assert_equal "2012-03-27 14:53:59 UTC", item_repo.find_by_updated_at("2012-03-27 14:53:59 UTC").updated_at end # find_all_by_id def test_it_returns_a_find_all_by_id_match assert_equal 1, item_repo.find_all_by_id("1").count assert_equal 1, item_repo.find_all_by_id("2").count end def test_it_returns_an_empty_array_when_no_find_all_by_id_match_exists assert_equal [], item_repo.find_all_by_id("0") assert_equal [], item_repo.find_all_by_id(" ") end def test_it_returns_zero_when_no_find_all_by_id_match_exists assert_equal 0, item_repo.find_all_by_id("0").count assert_equal 0, item_repo.find_all_by_id(" ").count end # find_all_by_name def test_it_returns_a_find_all_by_name_match assert_equal 3, item_repo.find_all_by_name("Item Qui Esse").count assert_equal 1, item_repo.find_all_by_name("Item Nemo Facere").count end def test_it_returns_an_empty_array_when_no_find_all_by_name_match_exists assert_equal [], item_repo.find_all_by_name("Item Qui Es") assert_equal [], item_repo.find_all_by_name(" ") end def test_it_returns_zero_when_no_find_all_by_name_match_exists assert_equal 0, item_repo.find_all_by_name("Item Qui Es").count assert_equal 0, item_repo.find_all_by_name(" ").count end # find_all_by_description def test_it_returns_a_find_all_by_description_match assert_equal 1, item_repo.find_all_by_description("Nihil autem sit odio inventore deleniti. Est laudantium ratione distinctio laborum. Minus voluptatem nesciunt assumenda dicta voluptatum porro.").count assert_equal 2, item_repo.find_all_by_description("cool thing").count end def test_it_returns_an_empty_array_when_no_find_all_by_description_match_exists assert_equal [], item_repo.find_all_by_description("super cool thing") assert_equal [], item_repo.find_all_by_description(" ") end def test_it_returns_zero_when_no_find_all_by_description_match_exists assert_equal 0, item_repo.find_all_by_description("super cool thing").count assert_equal 0, item_repo.find_all_by_description(" ").count end # find_all_by_unit_price def test_it_returns_a_find_all_by_unit_price_match assert_equal 1, item_repo.find_all_by_unit_price("75107").count assert_equal 3, item_repo.find_all_by_unit_price("58238").count end def test_it_returns_an_empty_array_when_no_find_all_by_unit_price_match_exists assert_equal [], item_repo.find_all_by_unit_price("55555") assert_equal [], item_repo.find_all_by_unit_price(" ") end def test_it_returns_zero_when_no_find_all_by_unit_price_match_exists assert_equal 0, item_repo.find_all_by_unit_price("55555").count assert_equal 0, item_repo.find_all_by_unit_price(" ").count end # find_all_by_merchant_id def test_it_returns_a_find_all_by_merchant_id_match assert_equal 15, item_repo.find_all_by_merchant_id("1").count assert_equal 9, item_repo.find_all_by_merchant_id("5").count end def test_it_returns_an_empty_array_when_no_find_all_by_merchant_id_match_exists assert_equal [], item_repo.find_all_by_merchant_id("55555") assert_equal [], item_repo.find_all_by_merchant_id(" ") end def test_it_returns_zero_when_no_find_all_by_merchant_id_match_exists assert_equal 0, item_repo.find_all_by_merchant_id("55555").count assert_equal 0, item_repo.find_all_by_merchant_id(" ").count end # find_all_by_created_at def test_it_returns_a_find_all_by_created_at_match assert_equal 99, item_repo.find_all_by_created_at("2012-03-27 14:53:59 UTC").count assert_equal 1, item_repo.find_all_by_created_at("2014-03-27 14:53:59 UTC").count end def test_it_returns_an_empty_array_when_no_find_all_by_created_at_match_exists assert_equal [], item_repo.find_all_by_created_at("1999") assert_equal [], item_repo.find_all_by_created_at(" ") end def test_it_returns_zero_when_no_find_all_by_created_at_match_exists assert_equal 0, item_repo.find_all_by_created_at("1999").count assert_equal 0, item_repo.find_all_by_created_at(" ").count end # find_all_by_updated_at def test_it_returns_a_find_all_by_updated_at_match assert_equal 99, item_repo.find_all_by_updated_at("2012-03-27 14:53:59 UTC").count assert_equal 1, item_repo.find_all_by_updated_at("2014-03-27 14:53:59 UTC").count end def test_it_returns_an_empty_array_when_no_find_all_by_updated_at_match_exists assert_equal [], item_repo.find_all_by_updated_at("1999") assert_equal [], item_repo.find_all_by_updated_at(" ") end def test_it_returns_zero_when_no_find_all_by_updated_at_match_exists assert_equal 0, item_repo.find_all_by_updated_at("1999").count assert_equal 0, item_repo.find_all_by_updated_at(" ").count end # RELATIONSHIPS def test_it_calls_sales_engine_to_find_invoice_items_by_item_id sales_engine = Minitest::Mock.new item_repo = ItemRepository.new(data, sales_engine) sales_engine.expect(:find_invoice_items_by_item_id, nil, [1]) item_repo.find_invoice_items_by_item_id(1) sales_engine.verify end def test_it_calls_sales_engine_to_find_merchant_by_merchant_id sales_engine = Minitest::Mock.new item_repo = ItemRepository.new(data, sales_engine) sales_engine.expect(:find_merchant_by_merchant_id, nil, [1]) item_repo.find_merchant_by_merchant_id(1) sales_engine.verify end end
require 'rails_helper' class FakeDeppContact include ActiveModel::Model def id 'test' end def name 'test' end def persisted? true end def password 'test' end def delete true end end RSpec.feature 'Contact deletion in registrar area' do given!(:registrar) { create(:registrar) } given!(:contact) { create(:contact, registrar: registrar) } background do allow(Depp::Contact).to receive(:find_by_id).and_return(FakeDeppContact.new) allow(Depp::Contact).to receive(:new).and_return(FakeDeppContact.new) sign_in_to_registrar_area(user: create(:api_user_with_unlimited_balance, registrar: registrar)) end it 'deletes contact' do visit registrar_contacts_url click_link_or_button 'Delete' confirm expect(page).to have_text('Destroyed') end private def confirm click_link_or_button 'Delete' end end
class LocationsController < ApplicationController def index country = params[:country] @locations = Location.search_country(country) json_response(@locations) end def show @location = Location.find(params[:id]) json_response(@location) end def create @location = Location.create!(location_params) json_response(@location, :created) end def update @location = Location.find(params[:id]) if @location.update!(location_params) render status: 200, json: { message: "Your location has been updated successfully." } end end def destroy @location = Location.find(params[:id]) if @location.destroy! render status: 200, json: { message: "Your location was deleted. Boom" } end end private def location_params params.permit(:country, :city) end end
class CreateBroFulfillments < ActiveRecord::Migration def change create_table :bro_fulfillments do |t| t.belongs_to :bro_order, index: true, foreign_key: true t.string :guid t.string :shipment_id t.string :tracking_number t.string :line_item_ids, array: true t.string :workflow_state t.text :notes t.datetime :shipped_at t.datetime :delivered_at t.timestamps null: false end add_index :bro_fulfillments, :guid end end
RSpec.describe "operation with documentation" do # see Test::Client definition in `/spec/support/test_client.rb` before do class Test::Client < Evil::Client operation do |settings| documentation "https://docs.example.com/v#{settings.version}/index.html" http_method :get path { "data" } end operation :clear_data operation :find_data do |settings| documentation "https://docs.example.com/v#{settings.version}/findData" end end stub_request(:any, //) end let(:client) { Test::Client.new("foo", version: 3, user: "bar") } it "displays default documentation in exception messages" do begin client.operations[:clear_data].call rescue => error expect(error.message).to include "https://docs.example.com/v3/index.html" else raise end end it "reloads default value with operation-specific one" do begin client.operations[:find_data].call rescue => error expect(error.message).to include "https://docs.example.com/v3/findData" else raise end end end
FactoryGirl.define do factory :manager do sequence(:email) {|n| "manager#{n}@willsmith.com"} sequence(:firstname) {|n| "manager#{n}"} password 'hhhhhh' approved true type "Manager" end end
module MCollective module Agent class Puppetca < RPC::Agent activate_when do require 'mcollective/util/puppetca/puppetca' true end def startup_hook @puppetca = Util::Puppetca.new end ['clean', 'revoke'].each do |command| action command do reply[:out] = @puppetca.clean(request[:certname]) end end action 'sign' do reply[:out] = @puppetca.sign(request[:certname]) end action 'list' do reply[:requests], reply[:signed] = @puppetca.certificates end action 'status' do status = @puppetca.status(request[:certname]) case status when 0 reply[:msg] = 'signed' when 1 reply[:msg] = 'awaiting signature' when 2 reply[:msg] = 'not found' else reply[:msg] = 'could not determine status of certificate: %s' % request[:certname] end end end end end
module Api class EventFormDataPresenter attr_reader :event, :default_role, :current_period def initialize(event) @event = event @default_role = event.default_role @current_period = PricingPeriod.current_period end def as_json(*) { registration_status: event.registration_status, event_price: event.event_prices.find_by(role: default_role, pricing_period: current_period).price, days: event_day_prices.map { |day_price| Api::DayPricePresenter.new(day_price) }, services: event_service_groups_with_service_prices } end private def event_day_prices default_role.day_prices.where(pricing_period: current_period) end def event_service_groups_with_service_prices event.service_groups.order(:id).inject([]) do |service_groups, service_group| service_groups << Api::ServiceGroupPresenter.new(service_group) if service_group.has_services_with_prices? service_groups end end end end
require 'json' class HabiticaClient class Restful < ApiBase class ServerError < IOError; end module ClassMethods def parse(client, attributes) new(client, remap(attributes)) end def remap(attributes) remapped = attributes.map do |k, v| [k.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase, v] end remapped.delete_if do |k, _v| k.match(/^_/) end Hash[remapped] end end extend ClassMethods def initialize(client, attributes = {}) self.attributes = attributes super(client) end def attributes=(attributes) attributes.each { |k, v| send("#{k}=", v) } end def new? id.nil? end def save response = put || post self.attributes = self.class.remap(response) self end def delete return nil if new? response = client.class.delete(url) response.ok? end def to_json to_h.to_json end private def url return "#{endpoint}/#{id}" unless new? endpoint end def request(method) response = client.class.send(method, url, body: to_json) unless response.response.code =~ /2\d{2}/ raise ServerError, response['err'] end response.parsed_response['data'] end def post return nil unless new? request(:post) end def put return nil if new? request(:put) end end end
# load './doc/preapproval.rb' require 'paypal-sdk-adaptivepayments' PayPal::SDK.load("config/paypal.yml", "test") @api = PayPal::SDK::AdaptivePayments::API.new # Build request object @preapproval = @api.build_preapproval({ :cancelUrl => "https://paypal-sdk-samples.herokuapp.com/adaptive_payments/preapproval", :currencyCode => "USD", :endingDate => 180.days.from_now.localtime, :maxAmountPerPayment => 1000.0, :maxNumberOfPayments => 1, :maxNumberOfPaymentsPerPeriod => 1, :maxTotalAmountOfAllPayments => 1000.0, :returnUrl => "https://paypal-sdk-samples.herokuapp.com/adaptive_payments/preapproval", :memo => "Contributing towards XXX project", :ipnNotificationUrl => "https://paypal-sdk-samples.herokuapp.com/adaptive_payments/ipn_notify", :senderEmail => "testus@impulsideas.com", :startingDate => Time.now, :pinType => "NOT_REQUIRED", :feesPayer => "PRIMARYRECEIVER", :displayMaxTotalAmount => false }) # Make API call & get response @preapproval_response = @api.preapproval(@preapproval) puts "\r\n@preapproval_response = #{@preapproval_response.inspect}" # Access Response if @preapproval_response.success? @preapproval_response.preapprovalKey else puts "\r\n@preapproval_response.error = #{@preapproval_response.error.map(&:message)}" end puts "\r\nhttps://www.sandbox.paypal.com/webscr?cmd=_ap-preapproval&preapprovalkey=#{@preapproval_response.preapprovalKey}"
class AddGameIndex < ActiveRecord::Migration def change add_index :games, :game_number add_index :games, :away_team_id add_index :games, :home_team_id end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: %i[google_oauth2 facebook] has_one :company, dependent: :destroy has_many :reviews, dependent: :destroy has_many :comments, dependent: :destroy validates :first_name, :last_name, presence: true def self.from_omniauth(access_token) data = access_token.info user = User.find_by(email: data['email']) if user.nil? user = User.create(email: data['email'], first_name: data['first_name'], last_name: data['last_name'], password: Devise.friendly_token[0, 20]) user.confirm end user end end
module ApplicationHelper def resource_name :member end def resource @resource ||= Member.new end def resource_class devise_mapping.to end def devise_mapping @devise_mapping ||= Devise.mappings[:member] end def flash_class(level) case level when "success" then "ui green message" when "error" then "ui red message" else "ui blue message" end end def title(page_title) content_for(:title) { page_title } end end
IAC = 255.chr # "\377" # "\xff" # interpret as command DONT = 254.chr # "\376" # "\xfe" # you are not to use option DO = 253.chr # "\375" # "\xfd" # please, you use option WONT = 252.chr # "\374" # "\xfc" # I won't use option WILL = 251.chr # "\373" # "\xfb" # I will use option SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation GA = 249.chr # "\371" # "\xf9" # you may reverse the line EL = 248.chr # "\370" # "\xf8" # erase the current line EC = 247.chr # "\367" # "\xf7" # erase the current character AYT = 246.chr # "\366" # "\xf6" # are you there AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently BREAK = 243.chr # "\363" # "\xf3" # break DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning NOP = 241.chr # "\361" # "\xf1" # nop SE = 240.chr # "\360" # "\xf0" # end sub negotiation EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode) ABORT = 238.chr # "\356" # "\xee" # Abort process SUSP = 237.chr # "\355" # "\xed" # Suspend process EOF = 236.chr # "\354" # "\xec" # End of file SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission OPT_ECHO = 1.chr # "\001" # "\x01" # Echo OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation OPT_STATUS = 5.chr # "\005" # "\x05" # Status OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type OPT_EOR = 25.chr # "\031" # "\x19" # End of Record OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List #MCCP OPT_COMPRESS = 85.chr OPT_COMPRESS2 = 86.chr OPT_MSSP = 70.chr MSSP_VAR = 1.chr MSSP_VAL = 2.chr NULL = "\000" CR = "\015" LF = "\012" EOL = CR + LF
class Product < ApplicationRecord belongs_to :supplier, foreign_key: 'supplier_id', class_name: 'User' has_many :orders, foreign_key: 'attended_order_id' has_many :ordereds, through: :orders validates :name, presence: true, length: { minimum: 2 } validates :description, presence: true, length: { in: 2..5000 } validates :quantity, presence: true end
module Config module Sources class YAMLSource attr_accessor :path def initialize(path) @path = path.to_s end def load if @path && File.exist?(@path.to_s) handler = ConfigHandler.new parser = Psych::Parser.new(handler) parser.parse(ERB.new(IO.read(@path)).result) result = handler.root.to_ruby.first end result || {} end end end end
require File.expand_path(File.dirname(__FILE__) + '/lib/item') require File.expand_path(File.dirname(__FILE__) + '/lib/order') require File.expand_path(File.dirname(__FILE__) + '/lib/line_item') require File.expand_path(File.dirname(__FILE__) + '/lib/line_item_parser') class Runner def initialize(*args) @items = File.read("input.txt") @line_items = @items.split("\n") end def print_packing_slip slip = ["%-8s%-16s%-12s%s" % ["Qty", "Item", "Price Each", "Total"]] order = Order.new @line_items.each do |raw_line_item| line_item = LineItemParser.parse(raw_line_item) order.add_line_item(line_item) end order.line_items.each do |line_item| slip << "%-8d%-16s$%-11.2f$%.2f" % [line_item.quantity, line_item.item_name, line_item.item_price, line_item.total] end slip << "Grand total: $%.2f" % [order.grand_total] slip += order.indications puts slip.join("\n").chomp end def self.run self.new(*ARGV).print_packing_slip end end Runner.run
# == Schema Information # # Table name: non_meetup_events # # id :bigint(8) not null, primary key # description_html :text(65535) # end_date :date # location :string(255) # start_date :date # title :string(255) # url :string(255) # created_at :datetime not null # updated_at :datetime not null # class NonMeetupEvent < ApplicationRecord scope :not_ended, -> { where('end_date >= ?', Date.today) } def present # For now we don't have a good way of displaying date ranges spanning # months so we just display the first date if start_date == end_date || start_date.month != end_date.month mday = start_date.mday.to_s wday = start_date.strftime('%A') else mday = "#{start_date.mday}-#{end_date.mday}" wday = "#{start_date.strftime('%a')}-#{end_date.strftime('%a')}" end { id: munged_id, url: url, title: title, month: start_date.strftime('%B'), mday: mday, wday: wday, location: location, description_html: description_html, } end def munged_id "nme-#{id}" end end
require_relative 'test_helper' require 'spelling_suggester' describe SpellingSuggester do include TestHelper describe "#lcs_len" do before do @suggester = SpellingSuggester.new sample_tuples end it "should find lcs_len" do assert_equal 8, @suggester.lcs_len("remimance", "remembrance") assert_equal 7, @suggester.lcs_len("remimance", "reminiscence") assert_equal 6, @suggester.lcs_len("immediately", "inndietlly") assert_equal 8, @suggester.lcs_len("incidentally", "inndietlly") end end describe "#each_tuples" do before do @suggester = SpellingSuggester.new sample_tuples end it "should enumerate each tuple" do expected_tuples = [ %w(remimance remembrance reminiscence), %w(inndietlly immediately incidentally) ] actual_tuples = [] @suggester.each_tuple do |tuple| actual_tuples.push(tuple) end assert_equal expected_tuples, actual_tuples end end end
class Api::CartItemsController < ApplicationController def index @cart_items = CartItem.all end def create @cart_item = CartItem.new(cart_item_params) @cart_item.user_id = current_user.id if @cart_item.save render :show else render json: @cart_item.errors.full_messages, status: 422 end end def update @cart_item = CartItem.find(params[:id]) @cart_item.update_attributes(cart_item_params) if @cart_item.save render :show else render json: @cart_item.errors.full_messages, status: 422 end end def destroy @cart_item = CartItem.find(params[:id]) @cart_item.destroy! render :show end private def cart_item_params params.require(:cartItem).permit(:user_id, :product_id, :size, :quantity) end end
class GoogleNestControl PROJECT_ID = ENV.fetch("PORTFOLIO_GCP_PROJECT_ID") CLIENT_ID = ENV.fetch("PORTFOLIO_GCP_CLIENT_ID") CLIENT_SECRET = ENV.fetch("PORTFOLIO_GCP_CLIENT_SECRET") REDIRECT_URI = "https://ardesian.com/nest_subscribe" BASE_URL = "https://smartdevicemanagement.googleapis.com/v1" attr_accessor :access_token, :refresh_token def self.code_url params = { redirect_uri: REDIRECT_URI, access_type: :offline, prompt: :consent, client_id: CLIENT_ID, response_type: :code, scope: "https://www.googleapis.com/auth/sdm.service", } "https://nestservices.google.com/partnerconnections/#{PROJECT_ID}/auth?#{params.to_query}" # Login and copy the `code` param from the redirect # then call GoogleNestControl.subscribe(code) # RefreshNestMessageWorker.perform_async end def self.subscribe(code) new.subscribe(code) # Remove from TODO ::User.me.lists.ilike(name: "Todo").take.list_items.by_formatted_name("Refresh Nest")&.soft_destroy end def initialize @access_token = DataStorage[:google_nest_access_token] @refresh_token = DataStorage[:google_nest_refresh_token] end def subscribe(code) auth( client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code: code, grant_type: :authorization_code, redirect_uri: REDIRECT_URI, ) self end def devices @devices ||= begin raise "No access token" if @access_token.blank? json = request(:get, "enterprises/#{PROJECT_ID}/devices") devices = json[:devices]&.map do |device_data| GoogleNestDevice.new(self).set_all(serialize_device(device_data)) end || [] DataStorage[:nest_devices] = devices.each_with_object({}) { |device, obj| obj[device.name] = device.to_json } devices end end def reload(device) json = request(:get, device.key) device.set_all(serialize_device(json)) end def set_mode(device, mode) mode = mode.to_s.upcase.to_sym raise "Must be one of: [cool, heat]" unless mode.in?([:COOL, :HEAT]) success = command( device, command: "sdm.devices.commands.ThermostatMode.SetMode", params: { mode: mode } )[:code] == 200 device.current_mode = mode.downcase.to_sym if success success end def set_temp(device, temp) mode = device.current_mode.to_s success = command( device, command: "sdm.devices.commands.ThermostatTemperatureSetpoint.Set#{mode.titleize}", params: { "#{mode.downcase}Celsius": f_to_c(temp) } )[:code] == 200 device.set_temp(mode.downcase.to_sym, temp) if success success end private def auth(params) raise "Should not auth in tests!" if Rails.env.test? res = RestClient.post("https://www.googleapis.com/oauth2/v4/token", params) json = JSON.parse(res.body, symbolize_names: true) @refresh_token = DataStorage[:google_nest_refresh_token] = json[:refresh_token] if json[:refresh_token].present? @access_token = DataStorage[:google_nest_access_token] = "#{json[:token_type]} #{json[:access_token]}" rescue RestClient::ExceptionWithResponse => err raise err rescue JSON::ParserError => err SlackNotifier.notify("Failed to auth Google Nest:\nCode: #{res.code}\n```#{res.body}```") end def refresh raise "No Refresh Token" if @refresh_token.blank? auth( client_id: CLIENT_ID, client_secret: CLIENT_SECRET, refresh_token: @refresh_token, grant_type: :refresh_token, ) end def request(method, url, params={}) raise "Should not request in tests!" if Rails.env.test? raise "Cannot request without access token" if @access_token.blank? retries ||= 0 res = ( if method == :get ::RestClient.get( "#{BASE_URL}/#{url}", base_headers.merge(params: params) ) elsif method == :post ::RestClient.post( "#{BASE_URL}/#{url}", params.to_json, base_headers ) end ) JSON.parse(res.body, symbolize_names: true).merge(code: res.code) rescue ::RestClient::ExceptionWithResponse => err retries += 1 return refresh && retry if retries < 2 && err.response.code == 401 ::SlackNotifier.notify("Failed to request from GoogleNestControl##{method}(#{url}):\nCode: #{res&.code}\n```#{params}```\n```#{res&.body}```") raise err rescue JSON::ParserError => err ::SlackNotifier.notify("Failed to parse json from GoogleNestControl##{method}(#{url}):\nCode: #{res&.code}\n```#{params}```\n```#{res&.body}```") raise "Failed to parse json from GoogleNestControl##{method}" end def base_headers { "Content-Type": "application/json", "Authorization": @access_token, } end def command(device, data) request(:post, "#{device.key}:executeCommand", data) end def serialize_device(device_data) { key: device_data.dig(:name), name: device_data.dig(:parentRelations, 0, :displayName), humidity: device_data.dig(:traits, :"sdm.devices.traits.Humidity", :ambientHumidityPercent).to_i, current_mode: device_data.dig(:traits, :"sdm.devices.traits.ThermostatMode", :mode).downcase&.to_sym, current_temp: c_to_f(device_data.dig(:traits, :"sdm.devices.traits.Temperature", :ambientTemperatureCelsius)), hvac: device_data.dig(:traits, :"sdm.devices.traits.ThermostatHvac", :status) == "ON", heat_set: c_to_f(device_data.dig(:traits, :"sdm.devices.traits.ThermostatTemperatureSetpoint", :heatCelsius)), cool_set: c_to_f(device_data.dig(:traits, :"sdm.devices.traits.ThermostatTemperatureSetpoint", :coolCelsius)), } end def c_to_f(c) return if c.blank? ((c * (9/5.to_f)) + 32).round end def f_to_c(ftemp) return if ftemp.blank? ((ftemp - 32) * (5/9.to_f)) end end
require 'uri' class Dependency < ActiveRecord::Base attr_accessible :name, :stage, :url validates :name, presence: true, uniqueness: {scope: :project_id}, format: {with: /\A\w.+\Z/, message: 'only words are allowed'} validates :url, format: {with: URI::regexp(%w(http https)), message: 'must be a valid http(s) url'}, allow_nil: true validates :stage, format: {with: /\A\w.+\Z/, message: 'only words are allowed'}, allow_nil: true validates_presence_of :project belongs_to :project # Dependencies listing (optionally for a particular project) def self.listing(prj_id = nil) deps = self.order('name asc') if prj_id.nil? # all dependencies deps.joins(:project).select('dependencies.*, '\ 'projects.name as project_name, '\ 'projects.website as project_website, '\ 'projects.description as project_description' ) else # dependencies for the project with id 'prj_id' deps.where('project_id = ?', prj_id) end # return end end
require 'grape' require 'grape-swagger' require 'grape-entity' module Keyta class Base < Grape::API version 'v1', using: :path, vendor: 'keyta' format :json prefix :api rescue_from :all error_formatter :json, ErrorFormatter mount Keyta::V1::Expeditions add_swagger_documentation( base_path: '/', mount_path: '/swagger_doc.json', swagger: '2.0', info: { title: 'KEYTA API V1.', description: 'A Akbar of the API for Keyta', contact_name: 'Akbar Maulana', contact_email: 'akbar.maulana090895@gmail.com', contact_url: 'https://resumtakbar.xyz', license: 'The Akbar of the license' }, markdown: false, hide_documentation_path: true, hide_format: true, included_base_url: true, api_version: 'v1' ) end end
# # Cookbook Name:: mysql-server # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # %w{mysql-server mysql-devel}.each do |pkg| package pkg do action :install end end template "my.cnf.erb" do path "/etc/my.cnf" source "my.cnf.erb" owner "root" group "root" mode 0644 end service "mysqld" do action [ :enable, :start] end execute "set root password" do #command "mysqladmin -u root password '#{node['mysql']['server_root_password']}'" command "mysqladmin -u root password 'Ken6en'" only_if "mysql -u root -e 'show databases;'" end directory "/home/mysql" do owner node['mysql']['user'] group node['mysql']['group'] mode 00755 action :create not_if { Dir.exists?("/home/#{node['mysql']['user']}") } end
class StateForRajyasabhaCandidates < ActiveRecord::Migration def self.up add_column :candidates, :state_id, :integer end def self.down remove_column :candidates, :state_id end end
require 'open-uri' require 'json' require 'oauth' class Twitter def initialize end def base_url(request_type) case request_type when 'search' return "https://api.twitter.com/1.1/search/tweets.json?" when 'users' return "https://api.twitter.com/1/users/lookup.json?" end end def hash_to_query_string(hash) query_string = String.new hash.each do |key, value| query_string += "#{key.to_s.downcase}=#{value.to_s.downcase}," end return query_string end def query_to_hash(request_type, query) base_url = base_url(request_type) url = URI.encode(base_url + query) result_json = open(url).read result = JSON.parse(result_json) return result end def users(args_hash) query = hash_to_query_string(args_hash) result = query_to_hash('users', query) end def search(args_hash) query = hash_to_query_string(args_hash) result = query_to_hash('search', query ) #result.length > 1? return result : return result.first return result end end
class BangladeshDisaggregatedDhis2Exporter STEP = 5 BUCKETS = (15..75).step(STEP).to_a def self.export exporter = Dhis2Exporter.new( facility_identifiers: FacilityBusinessIdentifier.dhis2_org_unit_id, periods: (current_month_period.advance(months: -24)..current_month_period), data_elements_map: CountryConfig.dhis2_data_elements.fetch(:disaggregated_dhis2_data_elements), category_option_combo_ids: CountryConfig.dhis2_data_elements.fetch(:dhis2_category_option_combo) ) exporter.export_disaggregated do |facility_identifier, period| region = facility_identifier.facility.region { htn_cumulative_assigned_patients: PatientStates::Hypertension::CumulativeAssignedPatientsQuery.new(region, period).call, htn_controlled_patients: PatientStates::Hypertension::ControlledPatientsQuery.new(region, period).call, htn_uncontrolled_patients: PatientStates::Hypertension::UncontrolledPatientsQuery.new(region, period).call, htn_patients_who_missed_visits: PatientStates::Hypertension::MissedVisitsPatientsQuery.new(region, period).call, htn_patients_lost_to_follow_up: PatientStates::Hypertension::LostToFollowUpPatientsQuery.new(region, period).call, htn_dead_patients: PatientStates::Hypertension::DeadPatientsQuery.new(region, period).call, htn_cumulative_registered_patients: PatientStates::Hypertension::CumulativeRegistrationsQuery.new(region, period).call, htn_monthly_registered_patients: PatientStates::Hypertension::MonthlyRegistrationsQuery.new(region, period).call, htn_cumulative_assigned_patients_adjusted: PatientStates::Hypertension::AdjustedAssignedPatientsQuery.new(region, period).call }.transform_values { |patient_states| disaggregate_by_gender_age(patient_states) } end end def self.disaggregate_by_gender_age(patient_states) gender_age_counts(patient_states).transform_keys do |(gender, age_bucket_index)| gender_age_range_key(gender, age_bucket_index) end end def self.gender_age_counts(patient_states) PatientStates::DisaggregatedPatientCountQuery.disaggregate_by_age( BUCKETS, PatientStates::DisaggregatedPatientCountQuery.disaggregate_by_gender(patient_states) ).count end def self.gender_age_range_key(gender, age_bucket_index) age_range_start = BUCKETS[age_bucket_index - 1] if age_range_start == BUCKETS.last "#{gender}_#{age_range_start}_plus" else age_range_end = BUCKETS[age_bucket_index] - 1 "#{gender}_#{age_range_start}_#{age_range_end}" end end def self.current_month_period @current_month_period ||= Period.current.previous end end
require 'rails_helper' RSpec.feature "The admin can deactivate various models" do context "Deactivate a model" do scenario "They deactivate a reservation" do admin = create(:user, role: 1) reservation = create(:reservation) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/reservations' click_on "Deactivate" expect(current_path).to eq('/admin/reservations') expect(Reservation.find(reservation.id).active).to eq(false) end scenario "They deactivate a planet" do admin = create(:user, role: 1) planet = create(:planet) spaces = create_list(:space, 3, approved: true, planet: planet) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/planets' within "#row-#{planet.name}" do click_on "Deactivate" end expect(current_path).to eq('/admin/planets') expect(Planet.find(planet.id).active).to eq(false) expect(Space.find(spaces[0].id).active).to eq(false) expect(Space.find(spaces[1].id).active).to eq(false) expect(Space.find(spaces[2].id).active).to eq(false) end scenario "They deactivate a space" do admin = create(:user, role: 1) space = create(:space, approved: true) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/spaces' click_on "Deactivate" expect(current_path).to eq('/admin/spaces') expect(Space.find(space.id).active).to eq(false) end scenario "They attempt to delete a style that has dependencies" do admin = create(:user, role: 1) style = create(:style) space = create(:space, style: style) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/styles' click_on "Delete" expect(current_path).to eq('/admin/styles') expect(Space.find(space.id)).to_not eq(false) end scenario "They attempt to delete a style that doesn't have dependencies" do admin = create(:user, role: 1) style = create(:style) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/styles' click_on "Delete" expect(current_path).to eq('/admin/styles') expect{Style.find(style.id)}.to raise_error(ActiveRecord::RecordNotFound) end scenario "They deactivate a user" do admin = create(:user, role: 1) spaces = create_list(:space, 3, approved: true) user = create(:user) user.spaces << spaces allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/users' within "#row-#{user.username}" do click_on "Deactivate" end expect(current_path).to eq('/admin/users') expect(User.find(user.id).active).to eq(false) expect(Space.find(spaces[0].id).active).to eq(false) expect(Space.find(spaces[1].id).active).to eq(false) expect(Space.find(spaces[2].id).active).to eq(false) end end context "Activate a model" do scenario "They activate a reservation" do admin = create(:user, role: 1) reservation = create(:reservation, active: false) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/reservations' click_on "Activate" expect(current_path).to eq('/admin/reservations') expect(Reservation.find(reservation.id).active).to eq(true) end scenario "They activate a planet" do admin = create(:user, role: 1) planet = create(:planet, active: false) spaces = create_list(:space, 3, approved: true, planet: planet, active: false) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/planets' within "#row-#{planet.name}" do click_on "Activate" end expect(current_path).to eq('/admin/planets') expect(Planet.find(planet.id).active).to eq(true) expect(Space.find(spaces[0].id).active).to eq(true) expect(Space.find(spaces[1].id).active).to eq(true) expect(Space.find(spaces[2].id).active).to eq(true) end scenario "They activate a space" do admin = create(:user, role: 1) space = create(:space, approved: true, active: false) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/spaces' click_on "Activate" expect(current_path).to eq('/admin/spaces') expect(Space.find(space.id).active).to eq(true) end scenario "They activate a user" do admin = create(:user, role: 1) spaces = create_list(:space, 3, approved: true, active: false) user = create(:user, active: false) user.spaces << spaces allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(admin) visit '/admin/users' within "#row-#{user.username}" do click_on "Activate" end expect(current_path).to eq('/admin/users') expect(User.find(user.id).active).to eq(true) expect(Space.find(spaces[0].id).active).to eq(true) expect(Space.find(spaces[1].id).active).to eq(true) expect(Space.find(spaces[2].id).active).to eq(true) end end end
class RsvpsController < ApplicationController def create rsvp = Rsvp.new(rsvp_params) if rsvp.save render :json => rsvp else render :json => rsvp.errors, :status => :unprocessable_entity end end def destroy rsvp = Rsvp.find(params[:id]) rsvp.destroy render json:rsvp end def index render :json => Rsvp.all end def show render :json => Rsvp.find(params[:id]) end def update rsvp = Rsvp.find(params[:id]) if rsvp.update_attributes(rsvp_params) render :json => rsvp else render :json => rsvp.errors, :status => :unprocessable_entity end end private def rsvp_params params.require(:rsvp).permit(:response, :guest) end end
# Class Example class Developer attr_reader :birthday attr_accessor :name def initialize(name,birthday) @name=name @birthday=birthday end def name=(name) @name=name end def birthday=(birthday) @birthday=birthday end def birthday @birthday end def name @name end end quincy=Developer.new("Quincy","1004") tina=Developer.new("Christina","0209") developers=[] developers.push(quincy) developers.push(tina) puts developers developers << quincy developers.each do |developer| puts "Name:#{developer.name}Birthday:#{developer.birthday}" end
# # Be sure to run `pod lib lint TGSDKText.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'TentSDK' s.version = '0.0.7' s.summary = 'TentSDK pod Use.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: 移动互联网出海一站式服务平台TigerSDK,通过对接一个SDK为单机、网游、APP提供登录、支付、数据跟踪、运营分析等多种功能。 DESC s.homepage = 'https://github.com/TigerSDK' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'liguoping@talentwalker.com' => 'liguoping@talentwalker.com' } s.source = { :git => 'https://github.com/TigerSDK/TentSDK.git', :tag => s.version.to_s }#你的仓库地址,不能用SSH地址 # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.requires_arc = true # 是否启用ARC # 设置默认的模块,如果在pod文件中导入pod项目没有指定子模块,导入的是这里指定的模块 s.default_subspec = 'TentFramework' # 定义一个核心模块,用户存放抽象的接口、基类以及一些公用的工具类和头文件 s.subspec 'TentFramework' do |subspec| # 配置系统Framework subspec.frameworks = 'UIKit', 'Foundation' subspec.resource = 'TentFramework/Assets/*.lproj','TentFramework/Assets/TentFramework.bundle' #你的SDK路径 subspec.vendored_frameworks = 'TentFramework/Classes/*.framework' end # 登录管理模块 s.subspec 'TentSDKLogin' do |login| # 添加依赖第三方的framework login.vendored_frameworks = 'TentSDKLogin/*.framework' # 依赖的核心模块 login.dependency 'TentSDK/TentFramework' end # 账号密码登录模块 s.subspec 'TentSDKLoginPw' do |loginPw| # 添加依赖第三方的framework loginPw.vendored_frameworks = 'TentSDKLoginPw/*.framework' # 依赖的核心模块 loginPw.dependency 'TentSDK/TentSDKLogin' end # Facebook登录模块 s.subspec 'TentSDKLoginFacebook' do |loginfb| # 添加依赖第三方的framework loginfb.vendored_frameworks = 'TentSDKLoginFacebook/*.framework' # 依赖的核心模块 loginfb.dependency 'TentSDK/TentSDKLogin' loginfb.dependency 'FBSDKCoreKit' loginfb.dependency 'FBSDKLoginKit' loginfb.dependency 'FBSDKShareKit' end # VK登录模块 s.subspec 'TentSDKLoginVK' do |loginvk| # 添加依赖第三方的framework loginvk.vendored_frameworks = 'TentSDKLoginVK/*.framework' # 依赖的核心模块 loginvk.dependency 'TentSDK/TentSDKLogin' loginvk.dependency 'VK-ios-sdk' end # Pay模块 s.subspec 'TentSDKPay' do |pay| # 添加依赖第三方的framework pay.vendored_frameworks = 'TentSDKPay/*.framework' # 配置系统Framework pay.frameworks = 'StoreKit' # 依赖的核心模块 pay.dependency 'TentSDK/TentFramework' end # AppsFlyerTracker模块 s.subspec 'TentSDKAppsFlyerTracker' do |appft| # 添加依赖第三方的framework appft.vendored_frameworks = 'TentSDKAppsFlyerTracker/*.framework' # 配置系统Framework appft.frameworks = 'AdSupport', 'iAd' # 依赖的核心模块 appft.dependency 'TentSDK/TentFramework' end # NanigansSDK模块 s.subspec 'TentSDKNanigansSDK' do |nanigans| # 添加依赖第三方的framework nanigans.vendored_frameworks = 'TentSDKNanigansSDK/*.framework' # 依赖的核心模块 nanigans.dependency 'TentSDK/TentFramework' end # Chartboost模块 s.subspec 'TentSDKChartboost' do |chartb| # 添加依赖第三方的framework chartb.vendored_frameworks = 'TentSDKChartboost/*.framework' # 依赖的核心模块 chartb.dependency 'TentSDK/TentFramework' end # FireBaseFCM推送模块 s.subspec 'TentSDKFireBaseFCM' do |firebasefcm| # 添加依赖第三方的framework firebasefcm.vendored_frameworks = 'TentSDKFireBaseFCM/*.framework' # 依赖的核心模块 firebasefcm.dependency 'TentSDK/TentFramework' firebasefcm.dependency 'Firebase/Core', '~> 5.4.0' firebasefcm.dependency 'Firebase/Messaging', '~> 5.4.0' end end
class CommentsController < ApplicationController before_filter :can_comment! before_filter :authenticate_admin!, only: [:destroy] def create @current_session = current_user || current_admin @comment = @current_session.comments.build(params[:comment]) if @comment.save flash[:success] = "Tu comentario ha sido publicado" redirect_to @comment.service_request else flash[:error] = @comment.errors.full_messages redirect_to :back end end def destroy @comment = Comment.find(params[:id]) @comment.destroy redirect_to @comment.service_request end private def can_comment! deny_access unless user_signed_in? or admin_signed_in? end end
class PortfoliosController < ApplicationController def index @portfolios = Portfolio.all end def new @portfolio = Portfolio.new end def create @portfolio = Portfolio.new(params[:portfolio]) if @portfolio.save redirect_to root_url, notice: "portfolio saved" else render action:new end end def show @portfolio = Portfolio.find(params[:id]) end def edit @portfolio = Portfolio.find(prams[:id]) end def destory @portfolio = Portfolio. find(params[:id]) @portfolio.destroy redirect_to root_url, notice: "portfolio destroyed" end end
class Classification < ActiveRecord::Base has_many :boat_classifications has_many :boats, through: :boat_classifications def self.my_all @classifications = Classification.all end def self.longest @boats = Classification.joins(:boats).order("boats.length DESC").limit(2) end end
class RenameCramListsToMemos < ActiveRecord::Migration def change rename_table :cram_lists, :memos end end
# coding: utf-8 require 'spec_helper' describe PaginateAlphabetically do before do @one = Thing.create!(:name => 'one') @two = Thing.create!(:name => 'two') @three = Thing.create!(:name => 'Three') @four = Thing.create!(:name => 'four') @five = Thing.create!(:name => 'Five') @six = Thing.create!(:name => 'Six') @nile = Container.create!(:name => 'nile', thing: @four) @stour = Container.create!(:name => 'stour', thing: @four) @avon = Container.create!(:name => 'avon', thing: @five) @amazon = Container.create!(:name => 'amazong', thing: @one) @danube = Container.create!(:name => 'danube', thing: @six) @rhine = Container.create!(:name => 'rhine', thing: @six) end after do Thing.destroy_all Container.destroy_all end context '#pagination_letters' do it 'picks out the correct letters from the set' do Thing.pagination_letters.should == ['F', 'O', 'S', 'T'] end it 'shows all letters always when asked' do Thing.paginate_alphabetically :by => :name, :show_all_letters => true Thing.pagination_letters.should == ('A'..'Z').to_a end end context "#first_letter" do it "is alphabetical" do Thing.create!(:name => ' o noes a space :(') Thing.create!(:name => '1') Thing.create!(:name => '®') Thing.create!(:name => '$') Thing.first_letter.should == 'F' end context "when there are no things" do it 'still works' do Thing.destroy_all Thing.first_letter.should == 'A' end end end context "alphabetical group" do it "works without specifying letter" do Thing.alphabetical_group.map(&:name).should == ['Five', 'four'] end it "works specifying letter" do Thing.alphabetical_group('t').map(&:name).should == ['Three', 'two'] end end context "class without pagination" do it "has no pagination methods" do lambda do Numpty.alphabetical_group end.should raise_error end end context 'associated pagination' do it 'is ' do Container.first_letter.should == 'F' end it 'picks out the correct letters from the set' do Container.pagination_letters.should == ['F', 'O', 'S'] end it "works without specifying letter" do Container.alphabetical_group.map(&:full_name).should == ['Five avon', 'four nile', 'four stour'] end it "works specifying letter" do Container.alphabetical_group('s').map(&:full_name).should == ['Six danube', 'Six rhine'] end end end
require 'rubygems' require 'eventmachine' require 'stomp_server/stomp_frame' require 'stomp_server/stomp_id' require 'stomp_server/stomp_auth' require 'stomp_server/topic_manager' require 'stomp_server/queue_manager' require 'stomp_server/queue' require 'stomp_server/queue/memory_queue' require 'stomp_server/queue/file_queue' require 'stomp_server/queue/dbm_queue' require 'stomp_server/protocols/stomp' module StompServer VERSION = '0.9.9' class Configurator attr_accessor :opts def initialize @opts = nil @defaults = { :port => 61613, :host => "127.0.0.1", :debug => false, :queue => 'memory', :auth => false, :working_dir => Dir.getwd, :storage => ".stompserver", :logdir => 'log', :monitor_sleep_time => 5, :configfile => 'stompserver.conf', :logfile => 'stompserver.log', :pidfile => 'stompserver.pid', :checkpoint => 0, :timeout => 10, :timeout_check_freq => 10 } @opts = getopts if opts[:debug] $DEBUG=true end end def getopts copts = OptionParser.new copts.on("-C", "--config=CONFIGFILE", String, "Configuration File (default: stompserver.conf)") {|c| @defaults[:configfile] = c} copts.on("-p", "--port=PORT", Integer, "Change the port (default: 61613)") {|p| @defaults[:port] = p} copts.on("-m", "--monitor-interval=TIME", Float, "Change the sleep time between monitor updates") {|p| @defaults[:monitor_sleep_time] = p} copts.on("-b", "--host=ADDR", String, "Change the host (default: localhost)") {|a| @defaults[:host] = a} copts.on("-q", "--queuetype=QUEUETYPE", String, "Queue type (memory|dbm|activerecord|file) (default: memory)") {|q| @defaults[:queue] = q} copts.on("-w", "--working_dir=DIR", String, "Change the working directory (default: current directory)") {|s| @defaults[:working_dir] = s} copts.on("-s", "--storage=DIR", String, "Change the storage directory (default: .stompserver, relative to working_dir)") {|s| @defaults[:storage] = s} copts.on("-d", "--debug", String, "Turn on debug messages") {|d| @defaults[:debug] = true} copts.on("-a", "--auth", String, "Require client authorization") {|a| @defaults[:auth] = true} copts.on("-c", "--checkpoint=SECONDS", Integer, "Time between checkpointing the queues in seconds (default: 0)") {|c| @defaults[:checkpoint] = c} copts.on("-t", "--timeout=SECONDS", Integer, 'Number of seconds to keep an unsent message in a queue') {|t| @defaults[:timeout] = t} copts.on("-f", "--freq=SECONDS", Integer, 'Interval between checking queues for timeout messages') {|f| @defaults[:timeout_check_freq] = f } copts.on("-h", "--help", "Show this message") do puts copts exit end puts copts.parse(ARGV) if File.exists?(@defaults[:configfile]) opts = @defaults.merge(YAML.load_file(@defaults[:configfile])) else opts = @defaults end opts[:etcdir] = File.join(opts[:working_dir],'etc') opts[:storage] = File.join(opts[:working_dir],opts[:storage]) opts[:logdir] = File.join(opts[:working_dir],opts[:logdir]) opts[:logfile] = File.join(opts[:logdir],opts[:logfile]) opts[:pidfile] = File.join(opts[:logdir],opts[:pidfile]) if opts[:auth] opts[:passwd] = File.join(opts[:etcdir],'.passwd') end return opts end end class Run attr_accessor :queue_manager, :auth_required, :stompauth, :topic_manager def initialize(opts) @opts = opts @queue_manager = nil @auth_required = nil @stompauth = nil @topic_manager = nil end def stop(pidfile) @queue_manager.stop puts "Stompserver shutting down" if $DEBUG EventMachine::stop_event_loop File.delete(pidfile) end def start begin if @opts[:group] puts "Changing group to #{@opts[:group]}." Process::GID.change_privilege(Etc.getgrnam(@opts[:group]).gid) end if @opts[:user] puts "Changing user to #{@opts[:user]}." Process::UID.change_privilege(Etc.getpwnam(@opts[:user]).uid) end rescue Errno::EPERM puts "FAILED to change user:group #{@opts[:user]}:#{@opts[:group]}: #$!" exit 1 end [:working_dir, :logdir, :etcdir ].each { |dir| Dir.mkdir(@opts[dir]) unless File.directory?(@opts[dir]) } if @opts[:daemon] Daemonize.daemonize(log_file=@opts[:logfile]) # change back to the original starting directory Dir.chdir(@opts[:working_dir]) end # Write pidfile open(@opts[:pidfile],"w") {|f| f.write(Process.pid) } qstore = case @opts[:queue] when 'dbm' StompServer::DBMQueue.new(@opts[:storage]) when 'file' StompServer::FileQueue.new(@opts[:storage]) when 'activerecord' require 'stomp_server/queue/activerecord_queue' StompServer::ActiveRecordQueue.new(@opts[:etcdir], @opts[:storage]) else StompServer::MemoryQueue.new end qstore.checkpoint_interval = @opts[:checkpoint] puts "Checkpoing interval is #{qstore.checkpoint_interval}" if $DEBUG @topic_manager = StompServer::TopicManager.new @queue_manager = StompServer::QueueManager.new(qstore, :timeout => @opts[:timeout], :timeout_check_freq => @opts[:timeout_check_freq], :monitor_sleep_time => @opts[:monitor_sleep_time]) @auth_required = @opts[:auth] if @auth_required @stompauth = StompServer::StompAuth.new(@opts[:passwd]) end trap("INT") { puts "INT signal received.";stop(@opts[:pidfile]) } end end end
#!/usr/bin/env ruby # $Revision: 1.2 $ # $Date: 2007-03-01 21:41:46 $ # my_name < email@example.com > # # DESCRIPTION: # USAGE: # LICENSE: ___ # ----------------------- creating synthesis tasks ----------------------- # # it's responsed for executing synthesis command and wrapping errors def synthesis_cmd (component, scrfile) Dir.chdir('synthesis') printf("%10s %s\n","synthesis:", component) FileUtils.mkdir_p(NGC_SCRATCHDIR) unless File.directory? NGC_SCRATCHDIR logfile = "#{NGC_SCRATCHDIR}/#{component}_xst.srp" cmd = %Q[xst -ifn #{scrfile} -ofn #{logfile} -intstyle silent] # p cmd %x[#{cmd}] # sh %Q[xst -ifn #{scrfile} -intstyle ise] if $?.exitstatus != 0 msg = "#-- \t Error: check '#{logfile}' for details.\n" $stderr.print( "#-- " + "-"*msg.size + " --#\n") $stderr.print(msg) $stderr.print( "#-- " + "-"*msg.size + " --#\n") puts %x[tail #{logfile}] $stderr.print( "#-- " + "-"*msg.size + " --#\n") exit end Dir.chdir('..') # move results to NGC_RESULTSDIR FileUtils.mkdir_p(NGC_RESULTSDIR) unless File.directory? NGC_RESULTSDIR ngcfile = "implementation/#{component}.ngc" FileUtils.mv(ngcfile, "#{NGC_RESULTSDIR}/") if File.file? ngcfile # remove xst temporary dir FileUtils.rm_rf("synthesis/xst") if File.directory? "synthesis/xst" end # input: prj source file # output: array with dependency filenames def parse_prjfile(src) result = Array.new File.open(src).each { |line| line =~ /(\S+)$/ # get filename file = $1 file.gsub!(/\.\.\//, '') file.gsub!(/^#{TMPDIR}\//, '') # remove tmpdir from the string if exists (such as in case of elaborate) result.push(file) } result end # generates synthesis task for each component def create_synthesis_tasks # Create filelist with vhd files hdlfiles = Dir["hdl/*.vhd"].delete_if { |x| x =~ /#{EXCLUDE_HDL}/ } # create synthesise task for each (vhdfile) component ngcfiles = Array.new # implementation/*.ngc scrfiles = Array.new # synthesis/*.scr prjfiles = Array.new # synthesis/*.prj hdlfiles.each { |vhdfile| component = vhdfile.gsub(/^hdl\/|.vhd$/,'') ngcfile = "#{NGC_RESULTSDIR}/#{component}.ngc" scrfile = "#{component}_xst.scr" prjfile = "#{component}_xst.prj" full_scrfile = "#{DESIGN_DIR}/synthesis/#{scrfile}" full_prjfile = "#{DESIGN_DIR}/synthesis/#{prjfile}" ngcfiles.push(ngcfile) # store for later scrfiles.push(scrfile) # store for later prjfiles.push(prjfile) # store for later # create synthesis task for each component unless Rake::Task.task_defined? ngcfile # p "adding task: #{component}" prj_deps = parse_prjfile(full_prjfile) file ngcfile => [vhdfile, full_scrfile, full_prjfile, prj_deps].flatten! do |t| puts t.investigation() if DEBUG synthesis_cmd(component, scrfile) end # check dependencies - they should exists # [full_scrfile, full_prjfile, prj_deps].flatten!.each { |dep_src| # file dep_src do # it will execute if there is no such file # $stderr.print "Error:\n" \ # "\tDon't know how to synthesis '#{vhdfile}'.\n" \ # "\t'#{full_scrfile}' is missing.\n" # exit; # end # } end } # add all components as dependencies # this is main synthesis task ngcfiles.delete(NGC_RESULTFILE) file NGC_RESULTFILE => ngcfiles end
class User < ActiveRecord::Base validates :name, presence: true has_many :posts, inverse_of: :post def to_s name end end
class CreateTransactions < ActiveRecord::Migration def change create_table :transactions do |t| t.references :user, index: true t.integer :amount, null: false t.string :currency, null: false t.string :customer_name t.integer :merchant_id t.string :merchant_name t.integer :product_id t.string :product_name t.string :transaction_id t.string :transaction_type t.timestamps end add_index :transactions, :merchant_id add_index :transactions, :product_id add_index :transactions, :transaction_id add_index :transactions, :transaction_type end end
require 'spec_helper' include Liquider::Ast include Liquider::ErbCompiler::Ast include Liquider::Spec describe Liquider::ErbCompiler do let(:compiler) { Liquider::ErbCompiler.new } before { target.visit(compiler) } context StringNode do let(:target) { StringNode.new("hello y'all") } it "escapes the strings" do expect(compiler.output).to eq("'hello y\\'all'") end end context BooleanNode do context "false" do let(:target) { BooleanNode.new(false) } it "outputs the value" do expect(compiler.output).to eq("false") end end context "true" do let(:target) { BooleanNode.new(true) } it "outputs the value" do expect(compiler.output).to eq("true") end end end context NumberNode do let(:target) { NumberNode.new(123.333) } it "outputs the number" do expect(compiler.output).to eq("123.333") end end context BooleanNode do let(:target) { BooleanNode.new(true) } it "outputs the boolean" do expect(compiler.output).to eq("true") end end context NilNode do let(:target) { NilNode.new } it "outputs nil" do expect(compiler.output).to eq("nil") end end context TagNode do let(:target) { TagNode.new(TestTag.new(:markup, DocumentNode.new([]))) } it "renders the tag" do expect_any_instance_of(TestTag).to receive(:render_erb).with(compiler) target.visit(compiler) end end context TextNode do let(:target) { TextNode.new("<%= toto %>") } it "escapes the erb out of it" do expect(compiler.output).to eq("<%%= toto %>") end end context MustacheNode do let(:target) { MustacheNode.new(StringNode.new("foo")) } it "wraps it's expression into an erb output node" do expect(compiler.output).to eq("<%= 'foo' %>") end end context NegationNode do let(:target) { NegationNode.new(NumberNode.new(5)) } it "negates the expression" do expect(compiler.output).to eq("!(5)") end end context BinOpNode do let(:target) { BinOpNode.new( :+, StringNode.new("foo"), StringNode.new("bar"), ) } it "adds spaces for sanity" do expect(compiler.output).to eq("'foo' + 'bar'") end end context CallNode do context 'litteral' do let(:target) { CallNode.new(StringNode.new("toto"), SymbolNode.new("length")) } it "doesn't send the symbol to the context" do skip expect(compiler.output).to eq("'toto'.length") end end context 'symbol' do let(:target) { CallNode.new( CallNode.new(SymbolNode.new("toto"), SymbolNode.new("titi")), SymbolNode.new("tata") ) } it 'delegates the call to the context' do expect(compiler.output).to eq("@context['toto.titi.tata']") end end end context IndexNode do let(:target) { IndexNode.new(SymbolNode.new("toto"), SymbolNode.new("property")) } it "sends the symbol to the context" do expect(compiler.output).to eq("@context['toto[property]']") end end context SymbolNode do let(:target) { SymbolNode.new("number") } it "sends the symbol to the context" do expect(compiler.output).to eq("@context['number']") end end context AssignNode do context "simple" do let(:target) { AssignNode.new(SymbolNode.new("toto"), StringNode.new("titi")) } it 'assigns a litteral' do expect(compiler.output).to eq("@context['toto'] = 'titi'") end end context "with filters" do let(:target) { AssignNode.new(SymbolNode.new('toto'), FilterNode.new( "filter1", ArgListNode.new([ SymbolNode.new("identifier") ], []) ) ) } it 'assigns to the context correctly' do expect(compiler.output).to eq("@context['toto'] = filter1(@context['identifier'])") end end end context CaseNode do let(:target) { CaseNode.new( SymbolNode.new('x'), [ WhenNode.new( NumberNode.new(0), DocumentNode.new([TextNode.new('foo')]) ), WhenNode.new( NumberNode.new(1), DocumentNode.new([TextNode.new('bar')]) ), CaseElseNode.new( DocumentNode.new([TextNode.new('quux')]) ), ] ) } it 'compiles case/when/else' do expected = "<% case @context['x'] %><% when 0 %>foo<% when 1 %>bar<% else %>quux<% end %>" expect(compiler.output).to eq(expected) end end context ForNode do let (:empty_body) { "do |_liquider_var_1| %><% @context['x'] = _liquider_var_1 %><% end %>" } context "simple for" do let(:target) { ForNode.new( SymbolNode.new('x'), CallNode.new(SymbolNode.new('foo'), SymbolNode.new('bar')), DocumentNode.new([ MustacheNode.new( CallNode.new(SymbolNode.new('x'), SymbolNode.new('title')) ), ]) ) } it 'compiles the body in an each loop and assigns to the context' do expect(compiler.output).to eq("<% @context['foo.bar'].each do |_liquider_var_1| %><% @context['x'] = _liquider_var_1 %><%= @context['x.title'] %><% end %>") end end context "for reversed" do let(:target) { ForNode.new( SymbolNode.new('x'), SymbolNode.new('foo'), DocumentNode.new([]), reversed: BooleanNode.new(true), ) } it "reverses the elements" do expect(compiler.output).to eq("<% @context['foo'].reverse.each " + empty_body) end end context "for with limit" do let(:target) { ForNode.new( SymbolNode.new('x'), SymbolNode.new('foo'), DocumentNode.new([]), limit: BinOpNode.new(:+, NumberNode.new(5), NumberNode.new(4)), ) } it "takes some elements" do expect(compiler.output).to eq("<% @context['foo'].take(5 + 4).each " + empty_body) end end context "for with offset" do let(:target) { ForNode.new( SymbolNode.new('x'), SymbolNode.new('foo'), DocumentNode.new([]), offset: BinOpNode.new(:+, NumberNode.new(5), NumberNode.new(4)), ) } it "drops some elements" do expect(compiler.output).to eq("<% @context['foo'].drop(5 + 4).each " + empty_body) end end context "with everything" do let(:target) { ForNode.new( SymbolNode.new('x'), SymbolNode.new('foo'), DocumentNode.new([]), offset: NumberNode.new(5), limit: NumberNode.new(5), reversed: BooleanNode.new(true), ) } it "combines drop/take/reverse" do expect(compiler.output).to eq("<% @context['foo'].drop(5).take(5).reverse.each " + empty_body) end end end context IfNode do context 'simple if' do let(:target) { IfNode.new( SymbolNode.new('foo'), DocumentNode.new([ TextNode.new('asdf') ]), NullNode.new ) } it 'compiles simple if nodes' do expect(compiler.output).to eq("<% if @context['foo'] %>asdf<% else %><% end %>") end end context 'if/else' do let(:target) { IfNode.new( SymbolNode.new('foo'), DocumentNode.new([ TextNode.new('asdf') ]), ElseNode.new( DocumentNode.new([ MustacheNode.new(SymbolNode.new('bar')) ]) ) ) } it 'compiles if/else branches' do expected = "<% if @context['foo'] %>asdf<% else %><%= @context['bar'] %><% end %>" expect(compiler.output).to eq(expected) end end context 'if/elsif/else' do let(:target) { IfNode.new( SymbolNode.new('foo'), DocumentNode.new([ TextNode.new('asdf') ]), IfNode.new( SymbolNode.new('quux'), DocumentNode.new([]), ElseNode.new( DocumentNode.new([ MustacheNode.new(SymbolNode.new('bar')) ]) ) ) ) } it 'compiles if/elsif/else branches' do expected = "<% if @context['foo'] %>asdf<% else %><% if @context['quux'] %><% else %><%= @context['bar'] %><% end %><% end %>" expect(compiler.output).to eq(expected) end end end context FilterNode do let(:target) { FilterNode.new( "filter2", ArgListNode.new([ FilterNode.new( "filter1", ArgListNode.new([ SymbolNode.new("identifier") ], []) )], [] ) ) } it 'unwraps filters correctly' do expect(compiler.output).to eq("filter2(filter1(@context['identifier']))") end end context ArgListNode do let(:target) { ArgListNode.new([ StringNode.new('arg1'), SymbolNode.new('variable') ], [ OptionPairNode.new( 'key', StringNode.new('value') ), OptionPairNode.new( 'other_key', SymbolNode.new('other_variable') ) ]) } it 'correctly outputs positionals and optionals' do expect(compiler.output).to eq("'arg1', @context['variable'], {'key' => 'value', 'other_key' => @context['other_variable']}") end end context ParenthesisedNode do let(:target) { ParenthesisedNode.new( BinOpNode.new( :/, ParenthesisedNode.new(BinOpNode.new(:+, NumberNode.new(1), NumberNode.new(3))), BinOpNode.new(:*, NumberNode.new(4), NumberNode.new(5)), ) ) } it "can be nested" do expect(compiler.output).to eq("((1 + 3) / 4 * 5)") end end context DocumentNode do let(:target) { DocumentNode.new([ MustacheNode.new( BinOpNode.new( :<, BinOpNode.new( :+, SymbolNode.new('foo'), BinOpNode.new( :*, StringNode.new('bar'), SymbolNode.new('baz'), ), ), NumberNode.new(40), ), ), TextNode.new("this is sparta") ]) } it "compiles the document" do expect(compiler.output).to eq("<%= @context['foo'] + 'bar' * @context['baz'] < 40 %>this is sparta") end end context HtmlTagNode do let(:target) { HtmlTagNode.new(:input, [OptionPairNode.new("type", SymbolNode.new("text"))]) } it 'renders tags with attributes' do expect(compiler.output).to eq('<input type="<%= @context[\'text\'] %>"/>') end end context HtmlBlockNode do let(:target) { HtmlBlockNode.new( :div, [OptionPairNode.new("class", StringNode.new("content"))], TextNode.new("a body") ) } it 'renders blocks with attributes' do expect(compiler.output).to eq(%(<div class="content">a body</div>)) end end context CaptureNode do let(:target) { CaptureNode.new("toto", HtmlTagNode.new(:div, [])) } it 'captures the body of the div' do expect(compiler.output).to eq("<% toto = capture do %><div/><% end %>") end end context LocalAssignNode do let(:target) { LocalAssignNode.new("toto", StringNode.new("titi")) } it 'assigns the variable to the local context' do expect(compiler.output).to eq("<% toto = 'titi' %>") end end context LocalFetchNode do let(:target) { MustacheNode.new(LocalFetchNode.new("toto")) } it 'renders correctly' do expect(compiler.output).to eq("<%= toto %>") end end context ContextStackNode do let(:target) { ContextStackNode.new(TextNode.new("text")) } it 'stacks context' do expect(compiler.output).to eq("<% @context.stack do %>text<% end %>") end end end
module Stator class Machine attr_reader :initial_state attr_reader :field attr_reader :transition_names attr_reader :transitions attr_reader :states attr_reader :namespace def initialize(klass, options = {}) @class_name = klass.name @field = options[:field] || :state @namespace = options[:namespace] @initial_state = options[:initial] && options[:initial].to_s @tracking_enabled = options[:track] || false @transitions = [] @aliases = [] # pushed out into their own variables for performance reasons (AR integration can use method missing - see the HelperMethods module) @transition_names = [] @states = [@initial_state].compact @options = options end def integration(record) ::Stator::Integration.new(self, record) end def get_transition(name) @transitions.detect{|t| t.name.to_s == name.to_s} end def transition(name, &block) t = ::Stator::Transition.new(@class_name, name, @namespace) t.instance_eval(&block) if block_given? verify_transition_validity(t) @transitions << t @transition_names |= [t.full_name] unless t.full_name.blank? @states |= [t.to_state] unless t.to_state.nil? t end def state_alias(name, options = {}, &block) a = ::Stator::Alias.new(self, name, options) a.instance_eval(&block) if block_given? @aliases << a a end def state(name, &block) transition(nil) do from any to name instance_eval(&block) if block_given? end end def tracking_enabled? @tracking_enabled end def conditional(*states, &block) _namespace = @namespace klass.instance_exec(proc { states.map(&:to_s).include?(self._stator(_namespace).integration(self).state) }, &block) end def matching_transition(from, to) @transitions.detect do |transition| transition.valid?(from, to) end end def evaluate @transitions.each(&:evaluate) @aliases.each(&:evaluate) generate_methods end def klass @class_name.constantize end protected def verify_transition_validity(transition) verify_state_singularity_of_transition(transition) verify_name_singularity_of_transition(transition) end def verify_state_singularity_of_transition(transition) transition.from_states.each do |from| if matching_transition(from, transition.to_state) raise "[Stator] another transition already exists which moves #{@class_name} from #{from.inspect} to #{transition.to_state.inspect}" end end end def verify_name_singularity_of_transition(transition) if @transitions.detect{|other| transition.name && transition.name == other.name } raise "[Stator] another transition already exists with the name of #{transition.name.inspect} in the #{@class_name} class" end end def generate_methods self.states.each do |state| method_name = [@namespace, state].compact.join('_') klass.class_eval <<-EV, __FILE__, __LINE__ + 1 def #{method_name}? integration = self._stator(#{@namespace.inspect}).integration(self) integration.state == #{state.to_s.inspect} end def #{method_name}_state_by?(time) integration = self._stator(#{@namespace.inspect}).integration(self) integration.state_by?(#{state.to_s.inspect}, time) end EV end end end end
class Admin::SubscribersController < Admin::AdminController def index @subscribers = Subscriber.all end end
class Property < ActiveRecord::Base has_many :images has_many :links mount_uploader :image,PropertyUploader extend FriendlyId friendly_id :slug_candidates, use: :slugged validates_presence_of :building_type, :address, :city, :state, :zip validates_uniqueness_of :address, scope: [:city, :state, :zip] validates :property_management_fee, :mortgage_payment, :hoa_fee, :property_tax, :hazard_insurance, numericality: { greater_than_or_equal_to: 0 } after_create :create_links scope :by_featured, -> (featured_arr) { where(:featured => featured_arr) } scope :active, -> { where(:active => true) } scope :not_sold, -> { where.not(:status => 'sold') } scope :by_status, -> (status) { where(:status => status) } scope :for_sale_and_reserved, -> { where status: [:for_sale, :reserved] } scope :by_building_type, -> (building_type) { where(building_type: building_type) } STATUS_ORDER = ['for_sale', 'reserved', 'sale_pending', 'sold', 'coming_soon'] STATES = {AL: 'Alabama', AK: 'Alaska', AS: 'American Samoa', AZ: 'Arizona', AR: 'Arkansas', CA: 'California', CO: 'Colorado', CT: 'Connecticut', DE: 'Delaware', DC: 'District of Columbia', FM: 'Federated States of Micronesia', FL: 'Florida', GA: 'Georgia', GU: 'Guam', HI: 'Hawaii', ID: 'Idaho', IL: 'Illinois', IN: 'Indiana', IA: 'Iowa', KS: 'Kansas', KY: 'Kentucky', LA: 'Louisiana', ME: 'Maine', MH: 'Marshall Islands', MD: 'Maryland', MA: 'Massachusetts', MI: 'Michigan', MN: 'Minnesota', MS: 'Mississippi', MO: 'Missouri', MT: 'Montana', NE: 'Nebraska', NV: 'Nevada', NH: 'New Hampshire', NJ: 'New Jersey', NM: 'New Mexico', NY: 'New York', NC: 'North Carolina', ND: 'north Dakota', MP: 'Northern Mariana Islands', OH: 'Ohio', OK: 'Oklahoma', OR: 'Oregon', PW: 'Palau', PA: 'Pennsylvania', PR: 'Puerto Rico', RI: 'Rhode Island', SC: 'South Carolina', SD: 'South Dakota', TN: 'Tennessee', TX: 'Texas', UT: 'Utah', VT: 'Vermont', VI: 'Virgin Islands', VA: 'Virginia', WA: 'Washington', WV: 'West Virginia', WI: 'Wisconsin', WY: 'Wyoming'} BUILDING_TYPES = [ ['All','single_family,duplex,fourplex,multifamily,commercial,townhouse'], ['Investment Homes', 'single_family,duplex,fourplex'], ['Multifamily','multifamily'], ['Commercial','commercial'] ] STATUS_OPTIONS = [ ['Select One',nil], ['Coming Soon',:coming_soon], ['For Sale',:for_sale], ['Reserved',:reserved], ['Sale Pending',:sale_pending], ['Sold',:sold], ['Not Active',:not_active] ] BUILDING_TYPE_OPTIONS = [ ['Select One',nil], ['Single Family',:single_family], ['Duplex',:duplex], ['Fourplex',:fourplex], ['Multifamily',:multifamily], ['Commercial',:commercial] ] def self.order_by_case query = "CASE" STATUS_ORDER.each_with_index do |s, i| query << " WHEN status = '#{s}' THEN #{i}" end query << " END" end scope :order_by_status, -> { order(order_by_case).order('updated_at DESC') } def raw_state STATES[self.state.to_sym] end def self.order_featured_properties(properties) properties.order('status ASC', 'updated_at DESC') end def create_links links = [{title: 'Community Overview'}, {title: 'Appraisal Tax Record'}, {title: 'Parcel Map'}, {title: 'Tax Statement'}, {title: 'School District'}, {title: 'Accident'}] links.each do |l| Link.create(property_id: id, title: l[:title]) end end def slug_candidates [ :title, [:address, :city, :state] ] end def raw_title self.title.present? ? self.title : raw_address end def raw_address "#{self.address.cap_each}, #{self.city.cap_each}, #{self.state.upcase}, #{self.zip}" if self.address.present? && self.city.present? && self.state.present? end def raw_map_address (self.address.present? && self.city.present? && self.state.present?) ? "#{self.address.cap_each}, #{self.city.cap_each}, #{self.state.upcase}, #{self.zip}" : self.title end def raw_offer_price helper.number_with_precision(self.offer_price,precision: 0,delimiter: ',') end def raw_cash_flow helper.number_with_precision(self.cash_flow,precision: 0,delimiter: ',') end def raw_rent helper.number_with_precision(self.rent,precision: 0,delimiter: ',') end def raw_status if self.status.present? self.status.humanize.cap_each else return nil end end def raw_school_district if self.school_district.present? self.school_district.humanize.cap_each else nil end end def raw_building_type self.building_type.humanize.cap_each end def chart return nil if !self.rent.present? || self.rent == 0 final = [] value = helper.number_with_precision(self.property_management_fee.to_f / 12.to_f,precision: 0) final << { title: 'Property Management', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } if self.property_management_fee.present? value = helper.number_with_precision(self.mortgage_payment,precision: 0) final << { title: 'Loan Payment', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } if self.mortgage_payment.present? && self.mortgage_payment > 0 value = helper.number_with_precision(self.hoa_fee.to_f / 12.to_f,precision: 0) final << { title: 'HOA', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } if self.hoa_fee.present? && self.hoa_fee > 0 value = helper.number_with_precision(self.property_tax.to_f / 12.to_f,precision: 0) final << { title: 'Property Tax', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } if self.property_tax.present? && self.property_tax > 0 value = helper.number_with_precision(self.hazard_insurance.to_f / 12.to_f,precision: 0) final << { title: 'Insurance', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } if self.hazard_insurance.present? && self.hazard_insurance > 0 if final.count > 0 && self.rent.present? total = 0.0 final.each do |val| total += val[:value].to_f end value = helper.number_with_precision(self.rent.to_f - total.to_f,precision: 0) value = self.cash_flow.round.to_i if self.cash_flow.present? final << { title: 'Cash Flow', value: value, raw_value: helper.number_with_precision(value,precision: 0,delimiter: ',') } return { rent: self.raw_rent, chart: final } else return nil end end # Begin import :-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-: def self.import file accepted_fields = [ 'address', 'city', 'zip', 'building_type', 'school_district', 'status', 'active', 'year_built', 'square_ft', 'lot_size', 'bedrooms', 'bathrooms', 'garages', 'offer_price', 'cash_flow', 'rent', 'leased', 'property_management_fee', 'mortgage_payment', 'hoa_fee', 'property_tax', 'hazard_insurance' ] errors = [] e = [] CSV.foreach(file.path, headers: true).with_index do |row, i| if row['address'].present? newRow = row.clone errors << row.headers.unshift('error') if i.zero? errors << row.fields.unshift('') if row['ignore'].eql?('header') data = row.clone.to_hash.slice( 'id', 'address', 'city', 'state', 'zip', 'building_type', 'school_district', 'status', 'active', 'year_built', 'square_ft', 'lot_size', 'bedrooms', 'bathrooms', 'garages', 'offer_price', 'cash_flow', 'rent', 'leased', 'property_management_fee', 'mortgage_payment', 'hoa_fee', 'property_tax', 'hazard_insurance' ) new_address = data['address'].clone if new_address.present? new_address.strip! number = new_address.match /[-\d\/]+/i new_address.gsub! /[-\d]+/i,'' new_address = "#{number} #{new_address}" new_address.gsub! /\(.+\)/i,'' new_address.strip! new_address.chomp! '/' new_address.strip! end data['address'] = new_address data['building_type'] = data['building_type'].parameterize.underscore if data['building_type'].present? data['status'] = data['status'].parameterize.underscore if data['status'].present? data['active'] = ['y','yes'].include?(data['active'].strip.downcase) if data['active'].present? data['offer_price'] = data['offer_price'].to_f * 1000 if data['offer_price'].present? data['leased'] = data['leased'].parameterize.underscore if data['leased'].present? # property = Property.find_by(address: data['address'],city: data['city'],state: data['state'],zip: data['zip']) || new(data) property = Property.find_by_id(data['id']) || new(data) if property.new_record? if !property.save errors << row.fields.unshift((property.errors.to_a.unshift('create')).to_s) # e << property.errors.to_a.unshift('create') << property.address end else if !property.update(data) errors << row.fields.unshift((property.errors.to_a.unshift('update')).to_s) # e << property.errors.to_a.unshift('update') << property.address end end end # ADDRESS not present end end # CSV loop end if errors.count > 1 csv_string = CSV.generate do |csv| errors.each_with_index do |item,i| csv << item end end end return csv_string end # End import :-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-: private def helper @helper ||= Class.new do include ActionView::Helpers::NumberHelper end.new end end
class AddDeliveryCompanyIdToDelivery < ActiveRecord::Migration def change add_column :deliveries, :delivery_company_id, :integer add_index :deliveries, :delivery_company_id end end
class TemplateController < ApplicationController attr_accessor :record attr_accessor :presenter def edit self.presenter = presenter end def update self.record = load_record self.record.attributes = permitted_params if self.record.save redirect_to [:edit, :template] else render 'edit' end end def data name = params[:name] template = presenter.templates.select do |template| template.name == name end.first render json: template.data end private def presenter @presenter ||= Template::EditPresenter.new end def load_record presenter.record end def permitted_params return {} unless params[:setting] params.require(:setting).permit(:value) end end
class Patient attr_reader(:name, :birthdate, :id, :doctor_id) define_method(:initialize) do |attributes| @name = attributes.fetch(:name) @birthdate = attributes.fetch(:birthdate) @doctor_id = nil @id = nil end define_method(:save) do patient = DB.exec("INSERT INTO patients (name) VALUES ('#{@name}') RETURNING id;") @id = patient.first().fetch('id').to_i() end define_singleton_method(:all) do patients = DB.exec("SELECT * FROM patients;") returned_patients = [] patients.each() do |patient| name = patient.fetch("name") birthdate = patient.fetch("birthdate") returned_patients.push(Patient.new({:name => name, :birthdate => birthdate})) end returned_patients end define_method(:==) do |another_patient| patient = self.birthdate().eql?(another_patient.birthdate()) patient_name = self.name().eql?(another_patient.name()) patient.&(patient_name) end define_method(:assign_doctor) do |scrubs| medic = scrubs.name returned_results = DB.exec("SELECT id FROM doctors WHERE name = ('#{medic}');") medic_ids = [] returned_results.each() do |id| whatever = id.fetch("id") medic_ids.push(whatever) end @doctor_id = medic_ids.first.to_i #grabs the first value in medic_id array and makes it an interger for @doctor_id DB.exec("UPDATE patients SET doctor_id = ('#{@doctor_id}') WHERE name = ('#{self.name}');") end end
require 'spec_helper' describe 'graphite::_web_packages' do context 'on centos' do before do stub_command('sestatus | grep enabled').and_return(true) end let(:chef_run) do ChefSpec::SoloRunner.new( platform: 'centos', version: '7' ).converge('graphite::web', described_recipe) end # it 'installs a django python package' do # expect(chef_run).to install_python_package('django') # end # it 'installs a specific version of graphite_web python package' do # expect(chef_run).to install_python_package('graphite_web').with( # package_name: 'graphite-web', # version: '1.1.3' # ) # end end end
# rubocop: disable Style/DoubleNegation # StringUtils # # Adding methods useful to string but avoiding monkey patching # module StringUtils extend ActiveSupport::Concern module ClassMethods # num? # # Detects if a string can be converted into a number # # Why am I writing, what would seem, a core function? Because Ruby takes the # string '10 Dowton' and converts using to_i to 10. This is not what I # desire - and indeed doesn't make much sense. # def num? str !!Integer(str) rescue ArgumentError, TypeError false end end end
class Order < ApplicationRecord PAYMENT_TYPES = ["Check", "Credit card", "Purchase order"] end
# == Schema Information # # Table name: mrcl_detail_records # # id :integer not null, primary key # representative_number :integer # representative_type :integer # record_type :integer # requestor_number :integer # policy_type :string # policy_number :integer # business_sequence_number :integer # valid_policy_number :string # manual_reclassifications :string # re_classed_from_manual_number :integer # re_classed_to_manual_number :integer # reclass_manual_coverage_type :string # reclass_creation_date :date # reclassed_payroll_information :string # payroll_reporting_period_from_date :date # payroll_reporting_period_to_date :date # re_classed_to_manual_payroll_total :float # created_at :datetime # updated_at :datetime # class MrclDetailRecord < ActiveRecord::Base require 'activerecord-import' scope :filter_by, -> (representative_number) { where(representative_number: representative_number) } def self.parse_table time1 = Time.new Resque.enqueue(ParseFile, "mrcls") time2 = Time.new puts 'Completed Mrcl Parse in: ' + ((time2 - time1).round(3)).to_s + ' seconds' end end
#stable, doesn't use extra memory: O(n**2) def insert_sort(arr) (1...arr.size).each do |i| key = arr[i] j = i-1 while key < arr[j] && j >= 0 arr[j+1] = arr[j] j -= 1 end arr[j+1] = key end arr end p insert_sort([4,3,6,1,2,7,8,5,9,0]) #stable, from O(logN) to O(n**2, when left is [], already sorted), recursive stack: O(N) def quick_sort(arr) return [] if arr.empty? first, *remaining = arr left, right = remaining.partition{ |x| x < first } quick_sort(left) + [first] + quick_sort(right) end p quick_sort([4,3,6,1,2,7,8,5,9,0]) def binary_search(arr, key) return -1 if arr.empty? min, max = 0, arr.size-1 while min <= max mid = min + (max - min) / 2 return mid if arr[mid] == key arr[mid] > key ? max = mid - 1 : min = mid + 1 end return -1 end ar = [23, 45, 67, 89, 123, 568] p binary_search(ar, 23) #0 p binary_search(ar, 123) #4 p binary_search(ar, 120) #-1 #swap all the time def bubble_sort(arr) for i in (arr.size-1).downto 0 do (0...i).each do |j| if arr[j] > arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] end end end arr end p bubble_sort([4,3,6,1,2,7,8,5,9,0]) #also selection sort: O(n**2), def cocktail_sort(arr) (0...arr.size/2).each do |f| (f...arr.size-f-1).each do |j| if arr[j] > arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] end for i in (arr.size-f-1).downto(1) do arr[i], arr[i-1] = arr[i-1], arr[i] if arr[i] < arr[i-1] end end end arr end p cocktail_sort([4,3,6,1,2,7,8,5,9,0]) #stable, O(N**2), need extra memeory def counting_sort(arr) work_list = Array.new(arr.max+1, 0) arr.each { |i| work_list[i] += 1 } result = [] work_list.each_with_index do |i, index| i.times {|j| result << index } if i != 0 end result end p counting_sort([7,20,12,3,2,2,2,1,1,0,0]) #[0, 0, 1, 1, 2, 2, 2, 3, 7, 12, 20] #need extra memeory: sorted, O(NlogN), stable def merge_sort(arr) return arr if arr.size == 1 #the last element, return array itself to end the recursion mid = arr.size / 2 left_arr = arr[0...mid] right_arr = arr[mid..-1] merge(merge_sort(left_arr), merge_sort(right_arr)) end def merge(left, right) sorted = [] until left.empty? || right.empty? sorted << (left.first <= right.first ? left.shift : right.shift) end sorted + left + right end p merge_sort([4,3,6,1,2,7,8,5,9,0]) # def shell_sort(arr) # size = arr.size # while (size = (size / 2)) >= 1 # puts size # (0...arr.size).each do |i| # break if i+size == arr.size # puts arr[i] # puts arr[i+size] # arr[i], arr[i+size] = arr[i+size], arr[i] if arr[i] > arr[i + size] # end # p arr # end # arr # end # # p shell_sort([4,3,6,1,2,7,8,5,9,0]) #find the max and min: use max heap or min heap, sort: NLogN def brackets(pairs, output='', open=0, close=0, arr = []) arr << output if open == pairs && close == pairs brackets(pairs, output + '(', open+1, close, arr) if open < pairs brackets(pairs, output + ')', open, close+1, arr) if close < open arr end p brackets(3) #["((()))", "(()())", "(())()", "()(())", "()()()"] def maximum_sub_array2(arr) current = [] max_sum = cur_sum = 0 max = (0...arr.size).inject([]) do |max, i| current << arr[i] cur_sum += arr[i] if cur_sum > max_sum max << i max_sum = cur_sum end max end arr[max[0]..max[-1]] end puts maximum_sub_array2([-1, 2, 5, -1, 3, -2, 1]).join(",") #2,5,-1,3 puts maximum_sub_array2([3, 1, -2, 5, 4, 5, 0, -3, 0, 3, 5, -3, -4, -3, 5]).join(",") #3,1,-2,5,4,5,0,-3,0,3,5 #use fisher yates shuffle agorithm def my_shuffle(arr) random_index = (0...arr.size).to_a.shuffle (0...arr.size).each do |i| index = random_index.pop arr[i], arr[index] = arr[index], arr[i] end arr end p my_shuffle([0,1,2,3,4,5,6,7,8,9])#[3, 5, 1, 4, 0, 2, 7, 8, 6, 9]
class Rating < ActiveRecord::Base attr_accessible :question_id, :rating, :product_review_id belongs_to :product_review belongs_to :question validates_presence_of :question_id, :rating, :product_review_id validates :rating, :numericality => { :greater_than_or_equal_to => 1 } def self.make_new_ratings(ratings, product_review_id) #params is an array of hashes new_ratings = ratings.collect do |rating| Rating.new(question_id: rating[:question_id], rating: rating[:rating], product_review_id: product_review_id) end if new_ratings.any?{ |rating| rating.invalid? } false else new_ratings.each(&:save) end end end
require 'test/unit' require 'yaml' class Load_documents_tests < Test::Unit::TestCase # def setup # end # def teardown # end def test_load_documents_from_string y = <<-EOF --- at: 2001-08-12 09:25:00.00 Z type: GET HTTP: '1.0' url: '/index.html' --- at: 2001-08-12 09:25:10.00 Z type: GET HTTP: '1.0' url: '/toc.html' EOF counter = 0 YAML::load_documents(y) do |doc| assert(doc.size == 4) if (counter == 0) assert(doc['type'] == 'GET') else assert(doc['url'] == '/toc.html') end counter += 1 end assert(counter == 2) end def test_load_documents_from_file counter = 0 y = File.open('yaml/yts_strangekeys.yml') YAML::load_documents(y) do |doc| if (counter == 0) assert(doc['ruby'] == 0.4) end counter += 1 end assert(counter == 3) end end
class InitSchema < ActiveRecord::Migration[5.2] def change # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" enable_extension "uuid-ossp" create_table "cart_items", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t| t.uuid "user_id" t.uuid "product_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["product_id"], name: "index_cart_items_on_product_id" t.index ["user_id"], name: "index_cart_items_on_user_id" end create_table "order_items", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t| t.string "name", null: false t.float "price", null: false t.float "discount", default: 1.0 t.float "actual_price", null: false t.uuid "product_id", null: false t.uuid "order_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "deleted_at" t.index ["deleted_at"], name: "index_order_items_on_deleted_at" t.index ["order_id"], name: "index_order_items_on_order_id" end create_table "orders", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t| t.float "price", null: false t.float "actual_price", null: false t.uuid "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "deleted_at" t.index ["deleted_at"], name: "index_orders_on_deleted_at" t.index ["user_id"], name: "index_orders_on_user_id" end create_table "products", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t| t.string "name", null: false t.text "description" t.float "price", null: false t.float "discount", default: 1.0 t.boolean "is_add", default: false t.uuid "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "deleted_at" t.index ["deleted_at"], name: "index_products_on_deleted_at" t.index ["user_id"], name: "index_products_on_user_id" end create_table "users", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t| t.string "email", null: false t.string "name", null: false t.integer "verify_code" t.string "introduction" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest", default: "", null: false t.string "role", default: [], null: false, array: true t.index ["email"], name: "index_users_on_email", unique: true end add_foreign_key "cart_items", "products" add_foreign_key "cart_items", "users" add_foreign_key "order_items", "orders" add_foreign_key "orders", "users" add_foreign_key "products", "users" end end
class CreateStandings < ActiveRecord::Migration[5.2] def change create_table :standings do |t| t.references :team t.references :season t.integer :wins t.integer :losses t.integer :ties t.timestamps end end end
#!/usr/bin/env ruby require 'optparse' require 'ostruct' def collectStems(dir,ext) currDir = Dir.getwd Dir.chdir(dir) files = Dir.glob("*.#{ext}") stems = Array.new for file in files do startIndex = 0 endIndex = file.index(".") - 1 stem = file[startIndex..endIndex] stems << stem end Dir.chdir(currDir) return stems end relPath = Dir.getwd Dir.chdir(File.dirname(__FILE__)) $:.push Dir.getwd #constants @WEKA_JAR = Dir.getwd + "/../lib/weka/weka.jar" @RESOURCES = Dir.getwd + "/../data" @CLASS_INDEX = 6 # set up options / defaults / user customization options = OpenStruct.new() options.inputType = Default_Input_Type = "txt" options.trainDir = Default_Train_Dir = Dir.getwd + "/../data/train" options.model = Default_Model_File = "#{@RESOURCES}/NaiveBayesSimple.model" opts = OptionParser.new do |opts| opts.banner = "usage: #{$0} [options]" opts.separator "" opts.on_tail("-h", "--help", "Show this message") do puts opts; exit end opts.on("-t", "--inputType [PROCESSTYPE]", "e.g., #{Default_Input_Type}/pdf") do |o| options.inputType = o end opts.on("-d", "--trainDir [TRAINDIR]", "default #{Default_Train_Dir}") do |o| options.trainDir = o end opts.on("-m", "--model [MODEL]", "default #{Default_Model_File}") do |o| options.model = o end end opts.parse!(ARGV) if options.trainDir != Default_Train_Dir and !File.exist?(options.trainDir) options.trainDir = "#{relPath}/#{options.trainDir}" end if !File.exist?(options.trainDir) puts "#{options.trainDir} not exist" exit end stems = collectStems(options.trainDir,"txt.final") for stem in stems do puts "Processing #{stem}" if options.inputType == "txt" #pdftotext & pos & stem" cmd = "ruby TXTProcessor.rb #{options.trainDir} #{stem}" else cmd = "ruby PDFProcessor.rb #{options.trainDir} #{stem}" end system(cmd) #np filter system("ruby NPFilter.rb #{options.trainDir} #{stem}") #write feat file end # Get name of model name_of_model = options.model.scan(/[^\/]+$/).first name_of_model = name_of_model.gsub(/\.[^\.]+$/, "") unless name_of_model[0] == "." # build dictionary cmd = "ruby DictionaryBuilder.rb #{options.trainDir} np > #{@RESOURCES}/#{name_of_model}-dictionary.txt" system(cmd) # build kp dictionary cmd = "ruby DictionaryBuilder.rb #{options.trainDir} kwd > #{@RESOURCES}/#{name_of_model}-kp_dictionary.txt" system(cmd) for stem in stems do system("ruby FeatWriter.rb #{options.trainDir} #{stem} #{@RESOURCES}/#{name_of_model}-dictionary.txt #{@RESOURCES}/#{name_of_model}-kp_dictionary.txt") end # write ARFF file system("ruby ARFFWriter.rb #{options.trainDir} #{@RESOURCES}/#{name_of_model}-train.arff") # discretize cmd = "java -cp #{@WEKA_JAR} weka.filters.supervised.attribute.Discretize -i #{@RESOURCES}/#{name_of_model}-train.arff -o #{@RESOURCES}/#{name_of_model}-train.discretized.arff -c #{@CLASS_INDEX}" system(cmd) # build model cmd = "java -cp #{@WEKA_JAR} weka.classifiers.bayes.NaiveBayesSimple -t #{@RESOURCES}/#{name_of_model}-train.discretized.arff -d #{options.model}" system(cmd)
class MultiplicationTable def initialize(size=9) @size = size end def header_row content_row(1) end def content #@content ||= (1..@size).map do |n| content_row(n) end end def to_s ' *' + header_row.map {|item| sprintf("%4d", item)}.join + "\n" + content.map.with_index do |item, index| content_row = item.map {|element| sprintf("%4d",element)}.join sprintf("%4d%s", index + 1, content_row) end.join("\n") + "\n" end private def content_row(multiplier) (1..@size).map do |n| n * multiplier end end end
Rails.application.routes.draw do devise_for :users resources :reservations root 'reservations#index' get '/reservations/:id/status', to: 'reservations#editstatus', as: 'edit_reservation_status' get '/reservations/:id/owner', to: 'reservations#edit_owner', as: 'reservation_owner' get '/reservations/:id/mailers', to: 'reservations#show_mailers', as: 'reservation_mailers' get 'reservations/:id/get_json', :controller=>"reservations", :action=>"get_json" patch '/reservations/:id/signature_received', to: 'reservations#signature_received', as: 'reservation_signature_received' get '/users', to: 'users#index', as: 'users' get '/users/deleted', to: 'users#deleted_index', as: 'deleted_users' get '/users/new', to: 'users#new', as: 'new_user' get '/user/:id', to: 'users#show', as: 'user' get '/users/:id/edit', to: 'users#edit', as: 'edit_user' post '/users', to: 'users#create' patch '/user/:id', to: 'users#update' delete '/user/:id', to: 'users#destroy' put '/user/:id/restore', to: 'users#restore', as: 'restore_user' get '/users/:id/editpw', to:'users#editpass', as: 'edit_user_pw' get '/groups', to: 'groups#index', as: 'groups' get '/groups/new', to: 'groups#new', as: 'new_group' get '/group/:id', to: 'groups#show', as: 'group' post '/groups', to: 'groups#create' get '/groups/:id/edit', to: 'groups#edit', as: 'edit_group' get '/groups/newmodal', to: 'groups#new_modal', :as => :new_group_modal patch '/group/:id', to: 'groups#update' get '/addresses', to: 'addresses#index', as: 'addresses' get '/addresses/new', to: 'addresses#new', as: 'new_address' get '/address/:id', to: 'addresses#show', as: 'address' post '/addresses', to: 'addresses#create' get '/brochures', to: 'brochures#index', as: 'brochures' get '/brochures/new', to: 'brochures#new', as: 'new_brochure' get '/brochure/:id', to: 'brochures#show', as: 'brochure' get '/brochures/:id/edit', to: 'brochures#edit', as: 'edit_brochure' post '/brochures', to: 'brochures#create' patch '/brochure/:id', to: 'brochures#update' delete '/brochure/:id', to: 'brochures#destroy' get '/brochures/archive', to: 'brochures#archive', as: 'archived_brochures' put '/brochures/:id/restore', to: 'brochures#restore', as: 'restore_brochure' get '/prizes', to: 'prizes#index', as: 'prizes' get '/prizes/new', to: 'prizes#new', as: 'new_prize' get '/prize/:id', to: 'prizes#show', as: 'prize' get '/prizes/:id/edit', to: 'prizes#edit', as: 'edit_prize' post '/prizes', to: 'prizes#create' patch '/prize/:id', to: 'prizes#update' delete '/prize/:id', to: 'prizes#destroy' get '/posters', to: 'posters#index', as: 'posters' get '/posters/new', to: 'posters#new', as: 'new_poster' get '/poster/:id', to: 'posters#show', as: 'poster' get '/posters/:id/edit', to: 'posters#edit', as: 'edit_poster' post '/posters', to: 'posters#create' patch '/poster/:id', to: 'posters#update' delete '/poster/:id', to: 'posters#destroy' get '/workgroups', to: 'workgroups#index', as: 'workgroups' get '/workgroups/new', to: 'workgroups#new', as: 'new_workgroup' get '/workgroup/:id', to: 'workgroups#show', as: 'workgroup' get '/workgroups/:id/edit', to: 'workgroups#edit', as: 'edit_workgroup' post '/workgroups', to: 'workgroups#create' patch '/workgroup/:id', to: 'workgroups#update' get '/regions', to: 'regions#index', as: 'regions' get '/regions/new', to: 'regions#new', as: 'new_region' get '/region/:id', to: 'regions#show', as: 'region' get '/regions/:id/edit', to: 'regions#edit', as: 'edit_region' post '/regions', to: 'regions#create' patch '/region/:id', to: 'regions#update' get '/packing_choices', to: 'packing_choices#index', as: 'packing_choices' get '/packing_choices/new', to: 'packing_choices#new', as: 'new_packing_choice' get '/packing_choice/:id', to: 'packing_choices#show', as: 'packing_choice' get '/packing_choices/:id/edit', to: 'packing_choices#edit', as: 'edit_packing_choice' post '/packing_choices', to: 'packing_choices#create' patch '/packing_choice/:id', to: 'packing_choices#update' get '/incentives', to: 'incentives#index', as: 'incentives' get '/incentives/new', to: 'incentives#new', as: 'new_incentive' get '/incentive/:id', to: 'incentives#show', as: 'incentive' get '/incentives/:id/edit', to: 'incentives#edit', as: 'edit_incentive' post '/incentives', to: 'incentives#create' patch '/incentive/:id', to: 'incentives#update' delete '/incentive/:id', to: 'incentives#destroy' get '/dashboard', to: 'dashboards#index', as: 'dashboard' get '/brochures_dash', to: 'dashboards#brochures_dash', as: 'brochures_dash' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
class Oystercard attr_reader :balance, :entry_station, :exit_station, :journeys MAX_LIMIT = 90 MIN_LIMIT = 1 MIN_FARE = 0 def initialize(balance=0) @balance = balance @entry_station @exit_station @journeys = {} end def top_up(amount) fail "Reached max limit of £90" if full? @balance += amount end def deduct(value) @balance -= value end def in_journey? !!entry_station end def touch_in(station) fail "Insufficient funds to touch in" if underfare? @in_journey = true @entry_station = station @journeys[:entry_station] = station p @journeys end def touch_out(station) deduct (MIN_FARE) @in_journey = false @entry_station = nil @exit_station = station @journeys[:exit_station] = station end private def full? @balance >= MAX_LIMIT end def underfare? @balance < MIN_LIMIT end end
require 'spec_helper' RSpec.describe Actions::ChangeApiTier do before do create(:tier, :free) end context 'with a previous tier' do let(:ultra_pod) { create(:api) } let(:tier) { create :tier, name: 'huge tier' } before do Timecop.travel(5.days.ago) { ultra_pod } described_class.new(api: ultra_pod, tier: tier).call end it "should set the new api's tier and deactivate the latter" do ultra_pod.reload.tap do |api| expect(api.tier).to eql tier expect(api.tier_usage.created_at).to be_within(1.day).of(Time.now) expect(api.tier_usages.first.deactivated_at).to be_within(1.day).of(Time.now) expect(api.tier_usage.deactivated_at).to be_nil end end end end
class Course < Event # includes attr_accessor :is_autocoached, :users_list, :coaches_list # Pre and Post processing # Enums # Relationships belongs_to :courseable, polymorphic: true belongs_to :theater belongs_to :user # Validations # validates_associated :user, :theater validates :event_date, presence: true validates :duration, presence: true, numericality: { greater_than_or_equal_to: 15 } # Scopes end
class AddRecordedByToClassPeriod < ActiveRecord::Migration[6.0] def change add_column :class_periods, :recorded_by, :string, :default => "" end end
# What will the following code print? Why? Don't run it until you've attempted to answer. def meal return 'Breakfast' 'Dinner' puts 'Dinner' end puts meal # meal explicitly returns 'Breakfast' without running the rest of the code within the method. puts meal will then print 'Breakfast'
# Логгер отправленных сообщений class MailLogger def self.delivered_email(mail) if mail[:user_id] && mail[:user_id].value.present? user = User.find(mail[:user_id].value) user.delivered_mails.create_by_mail!(mail) end end end
class AugmentIndexForCfsFileContentTypeWithName < ActiveRecord::Migration def change remove_index :cfs_files, :content_type_id add_index :cfs_files, [:content_type_id, :name] end end
puts 'Digite um número do mês em que você nasceu' month = gets.chomp.to_i # Quando a variavel é números você precisa colocar gets.chomp.TO_I para ela receber o numero, ao contrario do string que seria get.chomp case month when 1..3 puts 'Você nasceu no começo do ano' when 9..12 puts 'Você nasceu no final do ano' when 4..6 puts 'Você nasceu na primeira metade do ano!' when 7..9 puts 'Você nasceu na segunda metade do ano!' else puts 'Não foi possivel identificar' end
require_relative'../spec_helper' module Codebreaker RSpec.describe Console do subject(:console) {Console.new} let(:game) { console.instance_variable_get(:@game) } let(:game_code) { console.game.instance_variable_get(:@game_code) } context '#initialize' do it 'instance variables' do expect(console.game).to be_a_kind_of Codebreaker::Game expect(console.game_status).to eq(true) expect(console.hints).to eq(1) end end context "#hints" do it "reduce hints" do console.hint expect(console.hints).to eq(0) end it "game code include number of hint" do expect(console.game.instance_variable_get(:@game_code)).to include(console.hint) end it "player have no hints" do console.hint expect(console.hint).to eq("You have no hints") end end context '#win' do it 'return game win when guess = game code' do expect(subject.win(game.game_code)).to eq("You win!") end end context '#lose' do let(:chances) {subject.instance_variable_set(:@chances, 0)} it 'return game over when chanses = 0' do expect(subject.lose).to eq("Game over") end end context '#play_again' do it 'game start when player say Y' do allow(console).to receive(:gets).and_return("Y") expect { console.play_again }.to output(/again/).to_stdout end end context '#validation' do it 'guess must have 4 numbers' do expect { console.validation('12345') }.to raise_error RuntimeError expect { console.validation('123') }.to raise_error RuntimeError end it 'guess must to be a number' do expect { console.validation('1a45') }.to raise_error RuntimeError end it 'guess must contains number from 1 to 6' do expect { console.validation('1230') }.to raise_error RuntimeError expect { console.validation('1734') }.to raise_error RuntimeError end end context '#save' do it 'save game score to file' do console.save('score.yml') expect(File.exist?('score.yml')).to eq true expect{console.save}.to output(/game score saved/).to_stdout end end end end
RSpec.describe "An invitation" do let(:invitation) { spy("invitation") } before do invitation.deliver("foo@example.com") invitation.deliver("bar@example.com") end it "passes when a count constraint is satisfied" do expect(invitation).to have_received(:deliver).twice end it "passes when an order constraint is satisfied" do expect(invitation).to have_received(:deliver).with("foo@example.com") expect(invitation).to have_received(:deliver).with("bar@example.com") end it "fails when a count constraint is not satisfied" do expect(invitation).to have_received(:deliver).at_least(3).times end it "fails when an order constr end
require 'spec_helper' require 'sidekiq/testing' feature Admin, 'manages organizations:' do background do @admin = create(:super_user) given_logged_in_as(@admin) end scenario "sees organizations menu" do visit "/admin" expect(page).to have_link "Ver Organizaciones" click_on "Ver Organizaciones" expect(current_path).to eq(admin_organizations_path) end scenario "can create an new organization", js: true, skip: true do organization = FactoryGirl.build(:organization, :federal) visit "/admin/organizations" click_on 'Crear Organización' expect(current_path).to eq(new_admin_organization_path) fill_in('Nombre', with: organization.title) fill_in('Descripción', with: organization.description) fill_in('Sitio Web', with: organization.landing_page) select(organization.gov_type_i18n, from: 'organization_gov_type') click_on 'Guardar' sees_success_message "La organización se creó exitosamente." expect(current_path).to eq(admin_organizations_path) expect(page).to have_text(organization.title) expect(page).to have_text('Federal') end scenario "can edit an organization", js: true, skip: true do organization = FactoryGirl.create(:organization) new_attributes = FactoryGirl.attributes_for(:organization) visit "/admin/organizations" page.find("#organization_#{organization.id}").click click_on 'Editar' expect(current_path).to eq(edit_admin_organization_path(organization)) fill_in('Nombre', with: new_attributes[:title]) fill_in('Descripción', with: new_attributes[:description]) fill_in('Sitio Web', with: new_attributes[:landing_page]) select('Federal', from: 'organization_gov_type') click_on 'Guardar' organization.reload sees_success_message 'Se ha actualizado la organización exitosamente.' expect(current_path).to eq(admin_organizations_path) expect(page).to have_text(organization.title) expect(page).to have_text('Federal') end scenario 'can edit an organization', js: true, skip: true do organization = FactoryGirl.create(:organization) administrator = FactoryGirl.create(:user, organization: organization) liaison = FactoryGirl.create(:user, organization: organization) visit '/admin/organizations' page.find("#organization_#{organization.id}").click click_on 'Editar' expect(current_path).to eq(edit_admin_organization_path(organization)) select(administrator.name, from: 'organization_administrator_attributes_user_id') select(liaison.name, from: 'organization_liaison_attributes_user_id') click_on 'Guardar' organization.reload sees_success_message 'Se ha actualizado la organización exitosamente.' expect(current_path).to eq(admin_organizations_path) expect(organization.administrator.user.name).to eq(administrator.name) expect(organization.liaison.user.name).to eq(liaison.name) end scenario "can edit an organization gov_type", js: true, skip: true do organization = FactoryGirl.create(:organization) visit "/admin/organizations" page.find("#organization_#{organization.id}_gov_type").click click_on 'Cambiar a Estatal' sees_success_message 'Se ha actualizado la organización exitosamente.' expect(current_path).to eq(admin_organizations_path) expect(page).to have_text(organization.title) expect(page).to have_text('Estatal') end scenario "can add a sector", js: true, skip: true do create(:sector, title: 'Educación') organization = FactoryGirl.create(:organization) new_attributes = FactoryGirl.attributes_for(:organization) visit "/admin/organizations" page.find("#organization_#{organization.id}").click click_on 'Editar' expect(current_path).to eq(edit_admin_organization_path(organization)) click_on 'Agregar un sector' expect(page).to have_text('Eliminar sector') click_on 'Guardar' organization.reload sees_success_message 'Se ha actualizado la organización exitosamente.' expect(organization.sectors.count).to eq(1) end scenario "can delete a sector", js: true, skip: true do create(:sector, title: 'Educación') organization = FactoryGirl.create(:organization) new_attributes = FactoryGirl.attributes_for(:organization) visit "/admin/organizations" page.find("#organization_#{organization.id}").click click_on 'Editar' expect(current_path).to eq(edit_admin_organization_path(organization)) click_on 'Agregar un sector' click_on 'Guardar' sees_success_message 'Se ha actualizado la organización exitosamente.' visit "/admin/organizations" page.find("#organization_#{organization.id}").click click_on 'Editar' expect(current_path).to eq(edit_admin_organization_path(organization)) click_on 'Eliminar sector' click_on 'Guardar' organization.reload sees_success_message 'Se ha actualizado la organización exitosamente.' expect(organization.sectors.count).to eq(0) end scenario 'can create an new ministry' do visit new_admin_organization_path organization_attributes = attributes_for(:organization) fill_in('Nombre', with: organization_attributes[:title]) fill_in('Descripción', with: organization_attributes[:description]) fill_in('Sitio Web', with: organization_attributes[:landing_page]) find('select#organization_gov_type').find("option[value='#{organization_attributes[:gov_type]}']").select_option find(:css, '#organization_ministry').set(true) click_on 'Guardar' organization = Organization.find_by(title: organization_attributes[:title]) expect(organization.ministry?).to be true end scenario 'can convert an existing organization as a ministry' do organization = create(:organization) visit edit_admin_organization_path(organization) ministry_checkbox = find('#organization_ministry') expect(ministry_checkbox).not_to be_checked ministry_checkbox.set(true) click_on 'Guardar' expect(organization.reload.ministry?).to be true end end
class House attr_reader :name def initialize(name = 'Jack') @name = name end def recite lyrics(data.count) end def lyrics(n) song = [] 1.upto(n) do |verse| song << lyric(verse) end song.join("\n") end def lyric(n) "This is #{lines(n).join(' ')}" end def lines(n) data(name).last(n) end private def data(name = @name) ["the horse and the hound and the horn that belonged to", "the farmer sowing his corn that kept", "the rooster that crowed in the morn that woke", "the priest all shaven and shorn that married", "the man all tattered and torn that kissed", "the maiden all forlorn that milked", "the cow with the crumpled horn that tossed", "the dog that worried", "the cat that killed", "the rat that ate", "the malt that lay in", "the house that #{name} built."] end end