text
stringlengths
10
2.61M
#!/usr/bin/env ruby # Hpricot is an HTML/Web page processing library require "hpricot" puts "hpricot was loaded successfully" if defined? Hpricot
class Comment < ActiveRecord::Base validates :author_id, :post_id, :body, presence: true default_scope { order(created_at: :asc) } belongs_to :author, primary_key: :id, foreign_key: :author_id, class_name: :User belongs_to :post, primary_key: :id, foreign_key: :post_id, class_name: :Post end
require File.dirname(__FILE__) + '/sample_migration' require File.dirname(__FILE__) + '/../lib/spec/example/migration_example_group' describe :create_people_table, :type => :migration do before do run_migration end it 'should create a people table' do repository(:default).should have_table(:people) end it 'should have an id column as the primary key' do table(:people).should have_column(:id) table(:people).column(:id).type.should == 'int' table(:people).column(:id).should be_primary_key end it 'should have a name column as a string' do puts table(:people).inspect puts query("PRAGMA table_info(people)") table(:people).should have_column(:name) table(:people).column(:name).type.should == 'string' table(:people).column(:name).should_not permit_null end it 'should have a nullable age column as a int' do table(:people).should have_column(:age) table(:people).column(:age).type.should == 'int' table(:people).column(:age).should_not permit_null end end
class Question < ApplicationRecord belongs_to :subject, inverse_of: :questions has_many :answers accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true end
# модуль позволяет автоматом прописать # транслитерированный путь при создании экземпляра модели module SluggableModel extend ActiveSupport::Concern included do before_create :generate_slug def generate_slug self.slug = name.parameterize end def path self.class.name.underscore.pluralize + '/' + slug end end end
class Admin::UsersController < Admin::ApplicationController def index @users = User.all end def send_activation_email #TODO setup backend job system UserMailer.activation_email(user,params[:content]).deliver_later head :ok end def login login_as(user) redirect_to "/courses" end private def user user ||= User.find(params[:user_id]) end end
# Запись в блоге class Post < ActiveRecord::Base include SortedByName include MultilingualModel include AutotitleableModel include SluggableModel translates :announce, :title, :heading, :keywords, :description, :content default_scope { order(:weight) } has_many :post_comments has_many :post_blocks has_and_belongs_to_many :post_categories, join_table: :post_categories_posts belongs_to :blog_color validates :name, presence: true attr_accessor :picture has_attached_file :picture, styles: {admin: "30x30#", preview: "400x400#"}, default_url: "/images/:style/missing.png", url: "/uploads/blogs/:id/:style/:basename.:extension", path: ":rails_root/public/uploads/blogs/:id/:style/:basename.:extension" validates :picture, :attachment_presence => true validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/png','image/gif'] # генерация блоков в необходимой последовательности # - картинки группируются в галерею def grouped_blocks grouped = [] blocks.each do |b| block = {block: b, type: b.block_type} if 'picture' == b.block_type if grouped.last.kind_of?(Hash) and grouped.last[:type] == 'picture' else grouped << {type: 'picture', items: []} end grouped.last[:items] << block elsif 'html' == b.block_type if grouped.last.kind_of?(Hash) and grouped.last[:type] == 'html' else grouped << {type: 'html', items: []} end grouped.last[:items] << block else grouped << block end end grouped end # алиас def blocks post_blocks end # алиас def categories post_categories end # алиас def color blog_color end # алиас def comments post_comments end end
require 'rails_helper' require 'csv' RSpec.describe VanService do before(:each) do @service = VanService.new end it 'can connect with VAN upon initialization' do expect(@service).to be_truthy end it 'can find the id of a person' do survey_results_1_person = {:firstName=>"Vogelsang", :lastName=>"Daniel", :zipOrPostalCode=>80218, :phoneNumber=>"13162076632", :address=>["515 N Clarkson"], :city=>"Denver", :stateOrProvince=>"CO", :email=>"dr.vogelsang26@gmail.com", :responses=> {:canvassContext=>{:contactTypeId=>15, :inputTypeId=>11, :dataCanvassed=>'2017-11-04 21:08:19 -0600'}, :resultCodeId=>"null", :responses=> [{:surveyQuestionId=>123, :surveyResponseId=>1, :type=>"SurveyResponse"}, {:surveyQuestionId=>234, :surveyResponseId=>nil, :type=>"SurveyResponse"}, {:surveyQuestionId=>345, :surveyResponseId=>0, :type=>"SurveyResponse"}] } } id = @service.find_or_create(survey_results_1_person) expect(id).to eq(101073946) end xit 'can post canvass results given a known vanId' do id = 101073946 #works with or without canvassContext responses = {"canvassContext": { "contactTypeId": 2, "inputTypeId": 14, "dateCanvassed": "2012-04-09T00:00:00-04:00" }, "resultCodeId": "null", "responses": [{"activistCodeId": 4272694, "action": "Apply", "type": "ActivistCode"}, {"surveyQuestionId":268212, "surveyResponseId": 1118839, "type": "SurveyResponse"}, {"surveyQuestionId":268218, "surveyResponseId": 1118864, "type": "SurveyResponse"}, {"surveyQuestionId":268221, "surveyResponseId": 1118884, "type": "SurveyResponse"}] } results = @service.post(id, responses) end end
require "spec_helper" describe Lita::Handlers::Standups, lita_handler: true, additional_lita_handlers: Lita::Handlers::Wizard do include Lita::Standups::Fixtures before do Lita::User.create(2, name: "User2") Lita::User.create(3, name: "User3") create_standups(3) create_standup_schedules(3) create_standup_runs(3) robot.registry.register_hook(:validate_route, Lita::Extensions::Wizard) end after do cleanup_data end context "managing standups" do it "should list standups" do send_command("list standups") expect(replies.last).to match(/found: 3/) expect(replies.last).to match(/ID: 1/) end it "should start the create standup wizard" do expect_any_instance_of(described_class).to \ receive(:start_wizard).with(Lita::Standups::Wizards::CreateStandup, anything) send_command("create standup") end it "should create a standup" do expect do send_command("create standup") send_message("test-name", privately: true) send_message("q1", privately: true) send_message("q2", privately: true) send_message("done", privately: true) end.to change { Lita::Standups::Models::Standup.all.count }.by(1) end it "should show the details of a standup" do send_command("show standup 1") expect(replies.last).to match(/ID: 1/) expect(replies.last).to match(/Name:/) end it "should show an error message when trying to get the details of an inexisting standup" do send_command("show standup 100") expect(replies.last).to match(/I couldn't find a standup/) end it "should delete a standup" do expect do send_command("delete standup 1") end.to change { Lita::Standups::Models::Standup.all.count }.by(-1) expect(replies.last).to match(/Standup with ID 1 has been deleted/) end it "should show an error message when trying to delete an inexisting standup" do expect do send_command("delete standup 100") end.not_to change { Lita::Standups::Models::Standup.all.count } expect(replies.last).to match(/I couldn't find a standup/) end end context "managing standups schedules" do it "should start the wizard when trying to schedule a standup" do expect_any_instance_of(described_class).to \ receive(:start_wizard).with(Lita::Standups::Wizards::ScheduleStandup, anything, { "standup_id" => "1" }) send_command("schedule standup 1") end it "should show an error message when trying to schedule an inexisting standup" do expect do send_command("schedule standup 100") end.not_to change { Lita::Standups::Models::StandupSchedule.all.count } expect(replies.last).to match(/I couldn't find a standup/) end it "should schedule a daily standup" do expect do send_command("schedule standup 1") send_message("daily", privately: true) send_message("12:42pm", privately: true) send_message("user", privately: true) send_message("done", privately: true) send_message("#a", privately: true) end.to change { Lita::Standups::Models::StandupSchedule.all.count }.by(1) expect(replies.last).to match(/You're done!/) end it "should schedule a weekly standup" do expect do send_command("schedule standup 1") send_message("weekly", privately: true) send_message("tuesday", privately: true) send_message("12:42pm", privately: true) send_message("user", privately: true) send_message("done", privately: true) send_message("#a", privately: true) end.to change { Lita::Standups::Models::StandupSchedule.all.count }.by(1) expect(replies.last).to match(/You're done!/) end it "should delete a standup schedule" do expect do send_command("unschedule standup 1") end.to change { Lita::Standups::Models::StandupSchedule.all.count }.by(-1) expect(replies.last).to match(/Schedule with ID 1 has been deleted/) end it "should show an error message when trying to delete an inexisting standup schedule" do expect do send_command("unschedule standup 100") end.not_to change { Lita::Standups::Models::StandupSchedule.all.count } expect(replies.last).to match(/I couldn't find a scheduled standup/) end it "should list all standup schedules" do send_command("list standups schedules") expect(replies.last).to match(/Scheduled standups found: 3/) end it "should show details of a standup schedule" do send_command("show standup schedule 1") expect(replies.last).to match(/Here are the details/) expect(replies.last).to match(/ID: 1/) end it "should show an error message when trying to get the details of an inexisting standup schedule" do send_command("show standup schedule 100") expect(replies.last).to match(/I couldn't find a scheduled standup/) end end context "running standups" do it "should ask the robot to run a standup" do expect(robot).to receive(:run_standup).with("1", %w(user), anything) send_command("run standup 1 with user") end it "should show an error message when trying to run an inexisting standup schedule" do send_command("run standup 100 with user") expect(replies.last).to match(/I couldn't find a standup/) end it "should run a standup" do expect do send_command("run standup 1 with 1") send_message("a1", privately: true) send_message("done", privately: true) send_message("a2", privately: true) send_message("done", privately: true) send_message("a3", privately: true) send_message("done", privately: true) end.to change { Lita::Standups::Models::StandupSession.all.count }.by(1) end it "should be able to abort a running standup" do send_command("run standup 1 with 1") send_message("a1", privately: true) send_message("done", privately: true) send_message("abort", privately: true) expect(replies.last).to match(/Aborting/) end it "should list all standup sessions" do send_command("list standup sessions") expect(replies.last).to match(/Sessions found: 3. Here they are/) end it "should show the details of a standup sessions" do send_command("show standup session 1") expect(replies.last).to match(/Here are the standup session details/) expect(replies.last).to match(/ID: 1/) end it "should show an error message when trying to show an inexisting standup session" do send_command("show standup session 100") expect(replies.last).to match(/I couldn't find a standup session/) end end end
class UsersController < ApplicationController before_action :check_for_admin, :only => [:index] def index @users = User.all end def new @user = User.new end def create @user = User.new user_params if params["user"]["image"] cloudinary = Cloudinary::Uploader.upload( params[ "user" ][ "image" ] ) @user.image = cloudinary["url"] end if @user.save session[:user_id] = @user.id redirect_to user_path(@user) # Redirect to home if the account is valid else render :new # Let them retry the form again end end def show @user = User.find params[:id] results = Geocoder.search("#{@user.country}") coordinates = results.first.coordinates @latitude = coordinates.first @longitude = coordinates.last end def edit @user = User.find params[:id] end def update @user = User.find params[:id] if params["user"]["country"] results = Geocoder.search("#{@user.country}") coordinates = results.first.coordinates @latitude = coordinates.first @longitude = coordinates.last end @user.update user_params if params["user"]["image"] cloudinary = Cloudinary::Uploader.upload( params[ "user" ][ "image" ] ) @user.image = cloudinary["url"] end @user.save redirect_to @user end def destroy user = User.find params[:id] user.destroy redirect_to users_path end private def user_params params.require(:user).permit(:email, :password, :password_confirmation, :first_name, :last_name, :email, :bio, :country) end end
FactoryBot.define do factory :user do trait :invalid_name do name { nil } end trait :invalid_email do email { nil } end trait :invalid_password do password { nil } end trait :invalid_admin do admin { nil } end name { 'Valid name' } email { 'valid@mail.com' } password { '123123' } admin { true } provider { 'provider' } uid { 'randonuid' } end end
class CreateSettlementTables < ActiveRecord::Migration[5.2] def change create_table :settlement_tables do |t| t.integer :order_id t.string :namsettlement_state t.string :payment_method t.timestamps end end end
class Dog attr_accessor :name,:age, :breed @@all = [] def self.all @@all end def initialize(name = nil, breed = nil, age = nil) @name = name @breed = breed @age = age @@all << self end end
require 'rails_helper' RSpec.describe "Following relations", type: :feature do before(:each) do @user = create(:user) login_as @user, :scope => :user end it "follow user" do user2 = create(:user) expect { visit root_path click_link "btn-user-#{user2.id.to_s}" }.to change(Relation, :count).by(1) end it "unfollow user" do user2 = create(:user) Relation.create(user_id: @user.id, followed_id: user2.id) expect { visit root_path click_link "btn-user-#{user2.id.to_s}" }.to change(Relation, :count).by(-1) end it "shows followings" do user2 = create(:user) Relation.create(user_id: @user.id, followed_id: user2.id) visit root_path click_link "user-followings" expect(page).to have_content(user2.nickname) end it "shows followers" do user2 = create(:user) Relation.create(user_id: @user.id, followed_id: user2.id) visit root_path click_link "user-followers" expect(page).to have_content(@user.nickname) end end
class AddTotalsinvoice < ActiveRecord::Migration[5.2] def change add_column :quotations, :total_gross, :float end end
require 'test_helper' class Resources::ReviewsControllerTest < ActionController::TestCase def setup @controller.stub! :oauth_handshake, :return => true end # test "should get index" do # get :index # assert_response :success, @response.body # assert_not_nil assigns(:reviews) # end test "should get show" do get :show, :id => Factory(:review).to_param assert_response :success, @response.body assert_not_nil assigns(:review) end test "should get user tags" do get :user_tags, :id => Factory(:review).to_param assert_response :success, @response.body assert_not_nil assigns(:user_tags) end test "should get pros" do get :pros, :id => Factory(:review).to_param assert_response :success, @response.body assert_not_nil assigns(:pros) end test "should get cons" do get :cons, :id => Factory(:review).to_param assert_response :success, @response.body assert_not_nil assigns(:cons) end test "should get photos" do get :photos, :id => Factory(:review).to_param assert_response :success, @response.body assert_not_nil assigns(:photos) end test "should vote helpful" do post :helpful, :id => Factory(:review).to_param, :helpful => "yes" assert_response :success end test "should mark inappropriate" do # FIXME. @controller.instance_variable_set :@current_user, Factory(:user) post :inappropriate, :id => Factory(:review).to_param, :reason => "Curses" assert_response :success end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # user_name :string(255) not null # password_digest :string(255) not null # created_at :datetime # updated_at :datetime # class User < ActiveRecord::Base validates :user_name, presence: true, uniqueness: true validates :password_digest, presence: {message: "Password can't be blank"} # validates :session_token, presence:true validates :password, length: {minimum: 6, allow_nil: true} # after_initialize :ensure_session_token attr_reader :password has_many :cats has_many :rental_requests, through: :cats, source: :rental_requests has_many :placed_requests, class_name: 'CatRentalRequest', foreign_key: :user_id, primary_key: :id has_many :sessions def active_sessions sessions.where(active: true) end # create the jumbled hash def self.generate_session_token SecureRandom::urlsafe_base64(16) end # check if the info the user types in later matches a real user def self.find_credentials(user_name, password) user = User.find_by(user_name: user_name) return nil if user.nil? if user.is_password?(password) user else nil end end # make sure a newly created user has a session token # def ensure_session_token # self.session_token ||= User.generate_session_token # end # for logging out def reset_session_token!(user_agent) new_token = User.generate_session_token s = Session.create!(user_id: self.id, session_token: new_token, user_agent: user_agent) new_token # self.session_token = User.generate_session_token # self.save! # self.session_token end # creating or changing a password, creates the jumble and validates the length def password=(password) @password = password self.password_digest = BCrypt::Password.create(password) end # check if password matches db password def is_password?(password) BCrypt::Password.new(self.password_digest).is_password?(password) end end
require 'spec_helper' describe EventInfo do before do @valid_attributes ={ app_session_id: 1, event_id: 2, track_id: 3, time: 10.0, properties: { "name" => "John Doe" } } EventInfo.any_instance.stub(:associate_track) {} end it "should create a new install with valid attributes" do event_info = EventInfo.new(@valid_attributes) event_info.should be_valid end it "shouldn't create a new install with valid attributes" do event_info = EventInfo.new(@valid_attributes.merge(app_session_id: nil)) event_info.should be_invalid event_info = EventInfo.new(@valid_attributes.merge(event_id: nil)) event_info.should be_invalid event_info = EventInfo.new(@valid_attributes.merge(track_id: nil)) event_info.should be_invalid end describe "#by_properties" do it "should find events by properties" do event1 = EventInfo.create!(@valid_attributes.merge(properties: {name: "Paul", age: "20"})) event2 = EventInfo.create!(@valid_attributes.merge(properties: {name: "Paul", age: "18"})) event3 = EventInfo.create!(@valid_attributes.merge(properties: {name: "John", age: "20"})) EventInfo.by_properties(name: "Paul").should == [event1, event2] EventInfo.by_properties(name: "Paul", age: "20").should == [event1] EventInfo.by_properties(age: "20").should == [event1, event3] end end end
class CreateSecretWordsTable < ActiveRecord::Migration[6.0] def change create_table :secret_words do |t| t.string :word t.string :hint t.integer :difficulty end end end
class FlowsController < ApplicationController # TODO: show, editにset_flowメソッドを追加 def index @flow = Tflow.all().eager_load(:task) end def show @flow = Tflow.find(params['id']) end def new end def edit @flow = Tflow.find(params['id']) end def create end def update respond_to do |format| @flow = Tflow.find(params[:id]) if @flow.update(tflow_params) format.html { redirect_to flow_path(@flow.id) } format.json { render :show, status: :ok, location: @flow } else format.html { render :edit } format.json { render json: @flow.errors, status: :unprocessable_entity } end end end def destroy end def tflow_params params.require(:tflow).permit( :name, :description, task_attributes: [ :name, :description ] ) end end
class Topic < ActiveRecord::Base has_many :posts, dependent: :destroy has_many :playlists, dependent: :destroy validates :name, length: { minimum: 5 }, presence: true validates :description, length: { minimum: 10 }, presence: true scope :visible_to, lambda { |user| user ? scoped : where(public: true) } end
class CreateJoinTableUserDoc < ActiveRecord::Migration[5.1] def change create_join_table :users, :docs do |t| t.index [:user_id, :doc_id] t.index [:doc_id, :user_id] end end end
class Specie < ApplicationRecord has_many :person_species, class_name: "PersonSpecie", dependent: :destroy has_many :people, through: :person_species, source: :person validates :name, uniqueness: true end
require 'wsdl_mapper/dom/type_base' require 'wsdl_mapper/dom/shallow_schema' module WsdlMapper module Dom class BuiltinType < TypeBase NAMESPACE = 'http://www.w3.org/2001/XMLSchema'.freeze extend ShallowSchema self.namespace = NAMESPACE def root self end end end end
require 'rrreader/channel_item' module Rrreader class Channel attr_accessor :description, :title, :link, :items def initialize @items = [] end end end
class ApplicationController < ActionController::Base around_action :_set_locale_from_param before_action :_redirect_to_root_domain # before_action :_sleep_some_time def _sleep_some_time sleep 2 end def _set_locale_from_param locale = params[:locale] if params[:locale].present? && I18n.available_locales.include?(params[:locale].to_s.to_sym) locale ||= current_user&.locale || _get_locale_from_http_accept_language || I18n.default_locale I18n.with_locale locale.to_sym do # rubocop:todo Style/ExplicitBlockArgument yield end end def _get_locale_from_http_accept_language request.env['HTTP_ACCEPT_LANGUAGE'].to_s.scan(/^[a-z]{2}/).first end def _redirect_to_root_domain # request.host is www.movebase.link, request.domain is movebase.link return if request.host == request.domain return if request.host == '127.0.0.1' # return for system test redirect_to root_url(host: request.domain) end # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/PerceivedComplexity # To use, you need to initialize object and call with params and redirect path # redirect_path can be proc so it redirects to show page after create # Look for example admin/users_controller.rb # # def new # @subscriber = current_user.company.subscribers.new country: current_user.company.country # render partial: 'form', layout: false # end # def create # @subscriber = current_user.company.subscribers.new # update_and_render_or_redirect_in_js @subscriber, _subscriber_params, ->(subscriber) { subscriber_path(subscriber) } # end def update_and_render_or_redirect_in_js(item, item_params, redirect_path_or_proc = nil, partial = 'form', notice = nil) notice ||= if item.new_record? helpers.t_notice('successfully_created', item.class) else helpers.t_notice('successfully_updated', item.class) end item.assign_attributes item_params # if you need some custom checks you can add errors before calling this proc if item.errors.blank? && item.save flash[:notice] = flash.now[:notice] = notice redirect_path = if redirect_path_or_proc.instance_of? Proc redirect_path_or_proc.call item else redirect_path_or_proc end if redirect_path.present? render js: %( window.location.assign('#{redirect_path}'); ) else render js: %( window.location.reload(); ) end else flash.now[:alert] = item.errors.full_messages.to_sentence render js: _replace_remote_form_with_partial(partial) end end # rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/PerceivedComplexity def _replace_remote_form_with_partial(partial) %( var form = document.getElementById('remote-form'); var parent = form.parentNode; var new_form = document.createElement('div'); new_form.innerHTML = '#{helpers.j helpers.render(partial) + helpers.render('layouts/flash_notice_alert_jbox')}'; parent.replaceChild(new_form, form); ) end rescue_from ActionPolicy::Unauthorized do |exception| raise exception if Rails.env.development? message = "#{exception.message} #{exception.policy} #{exception.rule}" respond_to do |format| format.html { redirect_to root_path, alert: message } format.json { render json: { error_message: message, error_status: :bad_request }, status: :bad_request } end end # https://stackoverflow.com/questions/8224245/rails-routes-with-optional-scope-locale/8237800#8237800 def default_url_options(_options = {}) { locale: I18n.locale } end def after_sign_in_path_for(resource) helpers.request_path_with_locale stored_location_for(resource), resource.locale end end
# == Schema Information # # Table name: deployment_pipelines # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # name :string indexed # env_id :integer # position :integer # template :boolean default(TRUE) # deleted_at :datetime indexed # description :text # # Indexes # # index_deployment_pipelines_on_deleted_at (deleted_at) # index_deployment_pipelines_on_name (name) # describe DeploymentPipeline, type: :model do describe 'steps' do it { is_expected.to have_many(:steps).through(:deployment_pipeline_steps) } it 'should add step' do pipeline = DeploymentPipeline.create! step1 = Step.create!(name: 'step1') step2 = Step.create!(name: 'step2') pipeline.steps << step1 pipeline.steps << step2 expect(pipeline.steps.length).to eq 2 end end end
require 'spec_helper' describe GroupDocs::Api::Helpers::MIME do subject do GroupDocs::Signature.new end describe '#mime_type' do it 'returns first MIME type of file' do types = ['application/ruby'] ::MIME::Types.should_receive(:type_for).with(__FILE__).and_return(types) types.should_receive(:first).and_return('application/ruby') subject.send(:mime_type, __FILE__) end end end
require 'test_helper' class ShopInfosControllerTest < ActionController::TestCase setup do @shop_info = shop_infos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:shop_infos) end test "should get new" do get :new assert_response :success end test "should create shop_info" do assert_difference('ShopInfo.count') do post :create, shop_info: { address: @shop_info.address, lat: @shop_info.lat, lng: @shop_info.lng, name: @shop_info.name, photo: @shop_info.photo, shop_category_id: @shop_info.shop_category_id, tel: @shop_info.tel, url: @shop_info.url } end assert_redirected_to shop_info_path(assigns(:shop_info)) end test "should show shop_info" do get :show, id: @shop_info assert_response :success end test "should get edit" do get :edit, id: @shop_info assert_response :success end test "should update shop_info" do patch :update, id: @shop_info, shop_info: { address: @shop_info.address, lat: @shop_info.lat, lng: @shop_info.lng, name: @shop_info.name, photo: @shop_info.photo, shop_category_id: @shop_info.shop_category_id, tel: @shop_info.tel, url: @shop_info.url } assert_redirected_to shop_info_path(assigns(:shop_info)) end test "should destroy shop_info" do assert_difference('ShopInfo.count', -1) do delete :destroy, id: @shop_info end assert_redirected_to shop_infos_path end end
require 'rspec' require 'rack/test' describe 'CRUD Bookmark App' do include ::Rack::Test::Methods def app ::Sinatra::Application end describe 'POST /bookmarks' do it 'creates a new bookmark' do get '/bookmarks' expect(last_response).to be_ok bookmarks = ::JSON.parse(last_response.body) last_size = bookmarks.size post '/bookmarks', { :url => 'google.com', :title => 'Google' } expect(last_response.status).to eq(201) expect(last_response.body).to match(/\/bookmarks\/\d+/) get '/bookmarks' expect(last_response).to be_ok bookmarks = ::JSON.parse(last_response.body) expect(bookmarks.size).to eq(last_size + 1) end end describe 'PUT /bookmarks/:id' do it 'updates a bookmark' do post '/bookmarks', { :url => 'google.com', :title => 'Google' } expect(last_response.status).to eq(201) bookmark_uri = last_response.body bookmark_id = bookmark_uri.split('/').last put "/bookmarks/#{bookmark_id}", { :title => 'Success' } expect(last_response.status).to eq(204) get "/bookmarks/#{bookmark_id}" expect(last_response.status).to be_ok bookmark = ::JSON.parse(last_response.body) expect(bookmark['title']).to eq('Success') end end describe 'DELETE /bookmarks/:id' do it 'deletes a bookmark' do post '/bookmarks', { :url => 'google.com', :title => 'Google' } expect(last_response.status).to eq(201) bookmark_uri = last_response.body bookmark_id = bookmark_uri.split('/').last get "/bookmarks/#{bookmark_id}" expect(last_response.status).to be_ok delete "/bookmarks/#{bookmark_id}" expect(last_response.status).to be_ok get "/bookmarks/#{bookmark_id}" expect(last_response.status).to be_not_found end end end
class CreateUsers < ActiveRecord::Migration def up create_table :users do |t| t.column "first_name", :string, :limit => 25 #cria coluna nomeada first_name, do tipo string, com tamanho de 25 caracteres t.string "last_name", :limit => 50 #coluna string limite 50 caracteres t.string "email", :default => "", :null => false #coluna email com valor default "" e null = false indicando que não pode ser nulo t.string "password", :limit => 40 #coluna password com limite 40 caracteres #não precisa da coluna id, Rails implementa por default #t.datetime "created_at" #coluna do tipo datetime indicando a data de criação Rails popula automaticamente essa #t.datetime "updated_at" #coluna datetime indicando data de atualização Rails popula automaticamente essa t.timestamps null: false #versão simples das linhas acima end end def down drop_table :users end end
class CommentsController < ApplicationController before_filter :require_user def create @post = Post.find_by_slug(params[:post_id]) @comment = post.comments.new(params[:comment]) @comment.user = current_user if @comment.save redirect_to post_path(post) else render 'posts/show' end end end
module Fog module Compute class Google class MachineTypes < Fog::Collection model Fog::Compute::Google::MachineType def all(zone: nil, filter: nil, max_results: nil, order_by: nil, page_token: nil) opts = { :filter => filter, :max_results => max_results, :order_by => order_by, :page_token => page_token } if zone data = service.list_machine_types(zone, **opts).items else data = [] service.list_aggregated_machine_types(**opts).items.each_value do |scoped_list| data.concat(scoped_list.machine_types) if scoped_list && scoped_list.machine_types end end load(data.map(&:to_h) || []) end def get(identity, zone = nil) if zone machine_type = service.get_machine_type(identity, zone).to_h return new(machine_type) elsif identity # This isn't very functional since it just shows the first available # machine type globally, but needed due to overall compatibility # See: https://github.com/fog/fog-google/issues/352 response = all(:filter => "name eq #{identity}", :max_results => 1) machine_type = response.first unless response.empty? return machine_type end rescue ::Google::Apis::ClientError => e raise e unless e.status_code == 404 nil end end end end end
class PostsController < ApplicationController before_action :authenticate_user! def create @post = Post.new(post_params) @post.user_id = current_user.id @post.save flash[:create_post] = 投稿が完了しました! redirect_to posts_path end def show @user = current_user @new_post = Post.new @post = Post.find(params[:id]) @room = Room.new @rooms = @post.rooms end def edit @new_post = Post.new @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if params[:private] @post.update(flag:false) redirect_to user_path(current_user) elsif params[:open] @post.update(flag:true) redirect_to user_path(current_user) else if @post.update(post_params) flash[:update] = "記事を編集しました" redirect_to user_path(current_user) end end end def index @new_post = Post.new @q = Post.ransack(params[:q]) @posts = @q.result(distinct: true).where(flag: true).order(id: "DESC").page(params[:page]).per(12) @user = current_user end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to user_path(current_user) end def hashtag @new_post = Post.new @user = current_user @hashtag = Hashtag.find_by(hashname: params[:name]) @posts = @hashtag.posts.page(params[:page]).per(12) end private def post_params params.require(:post).permit(:title, :image, :body) end end
require 'spec_helper' describe Ecm::Tournaments::Tournament do context 'associations' do it { should belong_to :ecm_tournaments_series } it { should belong_to :ecm_tournaments_type } it { should have_many :ecm_tournaments_matches } it { should have_many :ecm_tournaments_participants } it { should have_many :ecm_tournaments_teams } end # context 'team creation' do # it { should respond_to(:create_and_randomize_teams) } # it 'should create the correct team count' do # tournament = FactoryGirl.create(:ecm_tournaments_tournament) # tournament.ecm_tournaments_participants = FactoryGirl.create_list(:ecm_tournaments_participant, 4) # tournament.create_and_randomize_teams # tournament.ecm_tournaments_teams.count.should eq(2) # end # it 'should create the correct team count for uneven participants number' do # tournament = FactoryGirl.create(:ecm_tournaments_tournament) # tournament.ecm_tournaments_participants = FactoryGirl.create_list(:ecm_tournaments_participant, 5) # tournament.create_and_randomize_teams # tournament.ecm_tournaments_teams.count.should eq(3) # end # end # context 'match generation' do # it { should respond_to(:generate_matches) } # it 'should generate the correct amount of matches' do # tournament = FactoryGirl.create(:ecm_tournaments_tournament) # tournament.ecm_tournaments_teams = FactoryGirl.create_list(:ecm_tournaments_team, 8, :ecm_tournaments_tournament => tournament) # tournament.generate_matches # tournament.ecm_tournaments_matches.count.should eq(7) # end # end context 'validations' do it { should validate_presence_of :begins_at } it { should validate_presence_of :ecm_tournaments_series } it { should validate_presence_of :ecm_tournaments_type } end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception #-- # Using Session include SessionsHelper #-- # Using RBAC include RBACAuthentication # find me at 'lib/rbac_authentication.rb' has_rbac_privileges({ ignore_unregistered: true, exceptions: ["home", "sessions"] }) #-- # Menu before_filter :fetch_menu private def fetch_menu @side_menu = [ { title: "Users", path: admin_users_path, method: "get" }, { title: "Roles", path: admin_roles_path, method: "get" }, { title: "Resources", path: admin_resources_path, method: "get" } ] end end
class RemoveApprove < ActiveRecord::Migration def change remove_column :transaction,:approve end end
class Student < ActiveRecord::Base has_many :attempts def self.find_by_formatted_organization_id(entered_id) self.find_by_organization_id(entered_id.upcase) end end
class CreateIndexesForUserIds < ActiveRecord::Migration def change remove_column :alexas, :user_id, :integer remove_column :stops, :user_id, :integer add_reference :alexas, :user, index: true, foreign_key: true add_reference :stops, :user, index: true, foreign_key: true end end
class Users::RegistrationsController < Devise::RegistrationsController def create @user = User.new sign_up_params if @user.save super else render json: {status: :error1, html: t(".error")} end end private def sign_up_params params.require(:user).permit :name, :email, :password, :password_confirmation end end
class Seed < ApplicationRecord has_one :fruit before_create :init scope :un_consumed, -> {where(consumed: false).order("RANDOM()").limit(1)} scope :consumed, -> {where(consumed: true).order(created_at: :desc).limit(10)} def attributes { id: id, label: label, consumed: consumed, fruit: { name: fruit.name } } end private def init self.label = "2-#{rand}" end end
require 'rails_helper' RSpec.describe "qualificacao_passagens/index", :type => :view do before(:each) do assign(:qualificacao_passagens, [ QualificacaoPassagem.create!( :concretizado => false, :justificativa => "Justificativa", :nivel => "Nivel", :comentario => "Comentario", :empresa_aerea => nil, :usuario => nil ), QualificacaoPassagem.create!( :concretizado => false, :justificativa => "Justificativa", :nivel => "Nivel", :comentario => "Comentario", :empresa_aerea => nil, :usuario => nil ) ]) end it "renders a list of qualificacao_passagens" do render assert_select "tr>td", :text => false.to_s, :count => 2 assert_select "tr>td", :text => "Justificativa".to_s, :count => 2 assert_select "tr>td", :text => "Nivel".to_s, :count => 2 assert_select "tr>td", :text => "Comentario".to_s, :count => 2 assert_select "tr>td", :text => nil.to_s, :count => 2 assert_select "tr>td", :text => nil.to_s, :count => 2 end end
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def when_deadline(month) if self.persisted? # 締切日から❍ヶ月後 self.deadline_on = months_later(month: month, time: deadline_on) # ここに余りがあれば足す処理追加 if self.respond_to?(:division_remainder) self.deadline_on = days_later(day: division_remainder, time: deadline_on) end deadline_on else # 締切を今日の日付 + ❍ヶ月後に設定 self.deadline_on = months_later(month: month) end end def months_later(month: 0, time: current_time) time.advance(months: month.to_i) end def days_later(day: 0, time: current_time) time.advance(days: day.to_i) end def current_time Time.zone.now end end
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :domain_name t.string :screen_name t.string :nickname t.text :profile_text t.integer :kitaguchi_profile_id t.boolean :random_url, :default => false t.string :random_key t.boolean :private, :default => false t.text :tags, :default => "{}" t.timestamps end end def self.down drop_table :users end end
class MessageBroadcastJob < ApplicationJob queue_as :default def perform(user, id) ActionCable.server.broadcast('messages', message: render_message(user), id: id) end private def render_message(user) ApplicationController.render(partial: 'messages/new_messages', locals: { user: user }) end end
require 'simplecov' SimpleCov.start require_relative '../lib/authentication.rb' require_relative '../lib/principal.rb' RSpec.describe Authentication do it 'can logout' do a = Authentication.new a.login(Principal.new('Sergio', 'Ramos', 'Director', 'pw2')) a.logout expect(a.logged).to be false end it 'can login' do a = Authentication.new pr = Principal.new('Sergio', 'Ramos', 'Director', 'pw2') a.login(pr) expect(a.logged).to be true expect(a.logged_principal).to eq(pr) end it 'before login where is no user' do a = Authentication.new expect(a.logged).to be false end end
require 'rails_helper' describe Location do before do mock_geocoding! end # allow mass assignment of describe "allow mass assignment of" do it { should allow_mass_assignment_of(:name) } it { should allow_mass_assignment_of(:address) } it { should allow_mass_assignment_of(:lat) } it { should allow_mass_assignment_of(:long) } it { should allow_mass_assignment_of(:rating) } it { should allow_mass_assignment_of(:city) } it { should allow_mass_assignment_of(:state) } it { should allow_mass_assignment_of(:country) } it { should allow_mass_assignment_of(:zip) } it { should allow_mass_assignment_of(:phone) } it { should allow_mass_assignment_of(:url) } it { should allow_mass_assignment_of(:location_images_attributes) } it { should allow_mass_assignment_of(:redemption_password) } it { should allow_mass_assignment_of(:bio) } it { should allow_mass_assignment_of(:token) } it { should allow_mass_assignment_of(:rsr_admin) } it { should allow_mass_assignment_of(:rsr_manager) } it { should allow_mass_assignment_of(:tax) } it { should allow_mass_assignment_of(:time_from) } it { should allow_mass_assignment_of(:full_address) } it { should allow_mass_assignment_of(:hour_of_operation) } it { should allow_mass_assignment_of(:chain_name) } it { should allow_mass_assignment_of(:timezone) } it { should allow_mass_assignment_of(:created_by) } it { should allow_mass_assignment_of(:last_updated_by) } it { should allow_mass_assignment_of(:info_id) } it { should allow_mass_assignment_of(:twiter_url) } it { should allow_mass_assignment_of(:facebook_url) } it { should allow_mass_assignment_of(:google_url) } it { should allow_mass_assignment_of(:instagram_username) } it { should allow_mass_assignment_of(:linked_url) } it { should allow_mass_assignment_of(:primary_cuisine) } it { should allow_mass_assignment_of(:secondary_cuisine) } it { should allow_mass_assignment_of(:com_url) } it { should allow_mass_assignment_of(:location_dates) } it { should allow_mass_assignment_of(:location_dates_attributes) } it { should allow_mass_assignment_of(:time_open) } it { should allow_mass_assignment_of(:time_close) } it { should allow_mass_assignment_of(:days) } end # Associations describe 'Associations' do it { should have_many(:location_comments).dependent(:destroy) } it { should have_many(:items).dependent(:destroy) } it { should have_many(:categories).dependent(:destroy) } it { should have_many(:notifications).class_name('Notifications').dependent(:destroy) } it { should have_many(:location_images).dependent(:destroy) } it { should have_many(:menus).dependent(:destroy) } it { should have_many(:servers).dependent(:destroy) } it { should have_many(:location_favourites).dependent(:destroy) } it { should have_many(:user_points).dependent(:destroy) } it { should have_many(:status_prizes).dependent(:destroy) } it { should have_many(:group).dependent(:destroy) } it { should have_many(:customers_locations).class_name('CustomersLocations').dependent(:destroy) } it { should have_many(:build_menus).through(:menus) } it { should have_many(:item_keys).dependent(:destroy) } it { should have_many(:location_visiteds).dependent(:destroy) } it { should have_many(:orders).dependent(:destroy) } it { should have_many(:hour_operations).dependent(:destroy) } it { should have_many(:checkins).dependent(:destroy) } it { should have_many(:location_dates).dependent(:destroy) } it { should have_one(:location_logo).dependent(:destroy) } it { should belong_to(:info) } it { should belong_to(:owner).class_name('User') } end describe "attr_accessor" do before :each do @location_attr_accessor = build(:location_attr_accessor) end it "returns a location object" do @location_attr_accessor.should be_an_instance_of Location end it "returns the correct full_address" do pending 'FIX asup' @location_attr_accessor.full_address.should eql "Banglore" end it "returns the correct hour_of_operation" do pending 'FIX asup' @location_attr_accessor.hour_of_operation.should eql "Monday" end it "returns the correct time_open" do @location_attr_accessor.time_open.should eql "11:20 AM" end it "returns the correct time_close" do @location_attr_accessor.time_close.should eql "11:30 PM" end it "returns the correct days" do @location_attr_accessor.days.should eql "Monday" end end # accepts_nested_attributes_for describe "accepts_nested_attributes_for" do it { should accept_nested_attributes_for(:location_dates) } xit { should accept_nested_attributes_for(:location_images)} end # Validations describe "Validations" do it { should validate_presence_of :address } it { should validate_presence_of :city } it { should validate_presence_of :country } it { should validate_presence_of :state } it { should allow_value("", nil).for(:phone) } it { should allow_value("", nil).for(:lat) } it { should allow_value("", nil).for(:long) } it { should allow_value("", nil).for(:rating) } it { should allow_value("", nil).for(:zip) } it { should allow_value("", nil).for(:tax) } end # Method describe "Method" do let(:location_build) {Location.new} before(:each) do @location_build = Location.new end context ".type" do it "Location.type should be mymenu" do @location_build.type.should eq("mymenu") end it "Location.type should not be blank" do @location_build.type.should_not eq("") end end context ".reference" do it "Location.reference should be blank" do @location_build.reference.should eq("") end it "Location.reference should not be fill" do @location_build.reference.should_not eq("test") end end context ".type_v1" do it "Location.type_v1 should be byte" do @location_build.type_v1.should eq("byte") end it "Location.type_v1 should not be blank" do @location_build.type_v1.should_not eq("") end end end describe 'when calling class method' do describe '.active_locations' do it 'should return an array' do expect(Location.active_locations).to eq([]) end end xdescribe '.all_nearby_including_unregistered' do it 'should return an array' do expect(Location.all_nearby_including_unregistered(DEFAULT_LATITUDE, DEFAULT_LONGITUDE).class).to eq(Array) end end xdescribe '.google_places_nearby_search' do it 'should return an array' do expect(Location.google_places_nearby_search(DEFAULT_LATITUDE, DEFAULT_LONGITUDE, 10).class).to eq(Array) end end xdescribe '.near_coordinates_with_ids' do it 'should return an array' do expect(Location.near_coordinates_with_ids(DEFAULT_LATITUDE, DEFAULT_LONGITUDE).class).to eq(Location::FriendlyIdActiveRecordRelation) end end xdescribe '.near_coordinates_with_name' do it 'should return an array' do expect(Location.near_coordinates_with_name(DEFAULT_LATITUDE, DEFAULT_LONGITUDE).class).to eq(Location::FriendlyIdActiveRecordRelation) end end end end
Rails.application.routes.draw do get '*path', to: "static#index", constraints: ->(request) do !request.xhr? && request.format.html? && !request.path.match(/^\/(assets|api)/) end root to: "static#index" end
begin require 'wesabe' module Bankjob class OutputFormatter class WesabeFormatter attr_accessor :username, :password, :account_number def initialize(credentials) @username, @password, @account_number = credentials.to_s.split(/ /, 3) if @username.blank? || @password.blank? raise ArgumentError, "You must specify a username and password (and optionally a target account number) to use Wesabe." end end def output(statement) ofx_formatter = OfxFormatter.new ofx_formatter.destination = StringIO.new("", 'w+') ofx_formatter.output(statement) ofx_formatter.destination.rewind ofx = ofx_formatter.destination.read wesabe = Wesabe.new(username, password) accounts = wesabe.accounts # FIXME: All these puts lines should really go to a logger. if accounts.empty? puts "You should create a bank account at http://wesabe.com/ before using this plugin." elsif account_number && !accounts.any? { |account| account.id == account_number.to_i } puts "You asked to upload to account number #{account_number} but your accounts are numbered #{accounts.map{|a| a.id}.join(', ')}." elsif !account_number && accounts.length > 1 puts "You didn't specify an account number to upload to but you have #{accounts.length} accounts." elsif account_number && account_number.to_i <= 0 puts "The account number must be between 1 and #{accounts.length} but you asked me to upload to account number #{account_number.to_i}." else self.account_number ||= 1 account = wesabe.account(account_number.to_i) uploader = account.new_upload uploader.statement = ofx uploader.upload! end end end end end rescue LoadError => exception module Bankjob class OutputFormatter class WesabeFormatter def initialize(*args) end def output(statement) msg = "Failed to load the Wesabe gem. Did you install it?\n" msg << "\n" msg << "Install the gem by running this as the administrator user (usually root):\n" msg << " gem install -r --source http://gems.github.com/ wesabe-wesabe" puts msg end end end end end
class AddColumnToMake < ActiveRecord::Migration[5.0] def change add_column :makes, :image, :string end end
module APND class Settings # # Settings for APND::MongoDB if you want persistence # class MongoDB attr_accessor :host attr_accessor :port attr_accessor :database def initialize @host = 'localhost' @port = 27017 @database = nil end def connect MongoMapper.connection = Mongo::Connection.new(@host, @port) MongoMapper.database = @database end end # # Returns the MongoDB settings # def mongodb @mongodb ||= APND::Settings::MongoDB.new end # # Mass assign MongoDB settings # def mongodb=(options = {}) if options.respond_to?(:keys) mongodb.port = options[:port] if options[:port] mongodb.host = options[:host] if options[:host] mongodb.database = options[:database] if options[:database] end end end end
require 'sinatra' class AllButPattern Match = Struct.new(:captures) def initialize(except) @except = except @captures = Match.new([]) end def match(str) @captures unless @except === str end end def all_but(pattern) AllButPattern.new(pattern) end get all_but('/index') do puts "GET all_but /index" end # Note that the above example might be over-engineered, as it can also be expressed as # get // do # pass if request.path_info == '/index' # # ... # end # get %r{?!/index} do # # ... # end
class AddBillableFlagToEvent < ActiveRecord::Migration def up add_column :events, :billable, :boolean, :default => true, :null => false Event.where(blackout: true).each do |e| e.update_column(:billable, false) end end def down drop_column :events, :billable end end
require 'pry-byebug' require 'sinatra' require 'rest-client' require 'json' require 'sinatra/base' class ListMore::Server < Sinatra::Application set :bind, '0.0.0.0' before do @body = request.body.read @body = "{}" if @body.length == 0 @params = JSON.parse(@body) puts "Got params: #{@params}" puts "PATH INFO: #{request.path_info.inspect}" pass if ['/', '/signup', '/signin'].include? request.path_info verified = ListMore::VerifyToken.run @params return {error: 'not authenticated'}.to_json unless verified end get '/' do send_file 'public/index.html' end post '/signup' do data = {} result = ListMore::SignUp.run @params puts result if result.success? data[:token] = result.token data[:user] = ListMore::Serializer.run result.user else status 403 return {error: "please fill out all fields"}.to_json end data.to_json end post '/signin' do data = {} result = ListMore::SignIn.run @params if result.success? data[:token] = result.token data[:user] = ListMore::Serializer.run result.user else status 403 return {error: "incorrect login credentials"}.to_json end data.to_json end post '/logout' do ListMore.sessions_repo.destroy @params['token'] end get '/users' do users = ListMore.users_repo.all data = users.map { |user| ListMore::Serializer.run user } { 'users' => data }.to_json end get '/users/:id' do user = ListMore.users_repo.find_by_id @params['id'] data = ListMore::Serializer.run user { 'user' => data }.to_json end get '/users/:id/lists' do user_lists = ListMore.lists_repo.get_user_lists @params['id'] shared_lists = ListMore.lists_repo.get_lists_shared_with_user @params['id'] lists_data = user_lists.map{ |list| ListMore::Serializer.run list} shared_lists_data = shared_lists.map{ |shared_list| ListMore::Serializer.run shared_list } { 'user_lists' => lists_data, 'shared_lists' => shared_lists_data }.to_json end post '/users/:id/lists' do puts "endpoint hit" # params = JSON.parse request.body.read list = ListMore::CreateList.run @params list_data = ListMore::Serializer.run list { 'list' => list_data }.to_json end put '/lists/:id' do result = ListMore::UpdateList.run @params # should i get all lists again here or "redirect" to get all lists for a user endpoint? if result.success? {success: true}.to_json else # some error end end delete '/lists/:id' do list = ListMore.lists_repo.find_by_id @params['id'] ListMore.lists_repo.destroy_list list # check for success end get '/lists/:id' do puts "GET list #{@params[:id]}" # puts request.body.read items = ListMore.items_repo.get_list_items @params['id'] items_data = items.map{ |item| ListMore::Serializer.run item } { 'items' => items_data }.to_json end post '/lists/:list_id/items' do item = ListMore::CreateItem.run @params item_data = ListMore::Serializer.run item { 'item' => item_data }.to_json end put '/items/:id' do result = ListMore::UpdateItem.run @params if result.success? {success: true}.to_json else # some error end end delete '/items/:id' do # params = JSON.parse request.body.read # puts params item = ListMore.items_repo.find_by_id @params['id'] ListMore.items_repo.destroy_item item.id # check for success end post '/share_list' do shared_list = ListMore::ShareList.run @params puts "this is the shared list data",shared_list shared_list_data = ListMore::Serializer.run shared_list # will serializer work in this context? { 'shared_list' => shared_list_data }.to_json end delete '/share_list/:id' do ListMore.shared_lists_repo.delete params # check for success end # post '/lists' do # user = ListMore::VerifyToken.run params # params[:user_id] = user.id # ListMore::CreateList.run params # end end # resources :posts do # resources :comments # end # delete '/comments/:id'
ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'shoulda/matchers' require 'capybara/rails' require 'capybara/rspec' require 'sidekiq/testing/inline' require 'webmock/rspec' require 'factory_girl' require 'pry' require 'mandrill_mailer/offline' Rails.application.routes.default_url_options[:host] = 'local.tipfortip.com' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } ActiveRecord::Migration.maintain_test_schema! # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' # Nyan! # config.formatter = NyanFormatter config.expect_with :rspec do |c| # disable the `should` syntax c.syntax = :expect end config.before(:each) do Rails.cache.clear end config.before(:each) { MandrillMailer.deliveries.clear } # rspec-rails 3 will no longer automatically infer an example group's spec type # from the file location. You can explicitly opt-in to this feature using this # snippet: config.infer_spec_type_from_file_location! WebMock.disable_net_connect!(allow_localhost: true) config.mock_with :rspec do |c| c.yield_receiver_to_any_instance_implementation_blocks = true end end
# == Schema Information # # Table name: wechat_sub_menus # # id :integer not null, primary key # wechat_menu_id :integer # menu_type :integer # name :string(255) # key :string(255) # url :string(255) # class WechatSubMenu < ActiveRecord::Base validates_presence_of :name, :menu_type validates_presence_of :key, if: -> { menu_type == 'click' } validates_presence_of :url, if: -> { menu_type == 'view' } validates :name, length: { maximum: 7 } belongs_to :wechat_menu, counter_cache: true def human_type WechatMenu::MENU_TYPES[self.menu_type.to_sym] if self.menu_type end def human_key WechatMenu::KEYS[self.key.to_sym] if self.key end end
class SpeakerArea < ActiveRecord::Base belongs_to :speaker belongs_to :area end
class TestAuthenticationController < ApplicationController before_action :authenticate_user! def index render json: { message: 'Message Success!' }, status: :ok end end
class AddNeighborhoodToDeliverCoordinators < ActiveRecord::Migration def change add_column :deliver_coordinators, :neighborhood, :string, null: false, default: '' end end
class GcmNotificationController < ApplicationController before_filter :authenticate_user! before_filter :set_app layout 'gcms_notification_menu' def notification @notification = Rapns::Gcm::Notification.new end def create @notification = Rapns::Gcm::Notification.new(notification_params) @notification.app = @app @notification.registration_ids = @app.app_users.select(:auth_key).map(&:auth_key) respond_to do |format| if @notification.save format.html{redirect_to ({:action => 'show', :app_name => @app.name, id:@notification.id}), notice: 'Notification was successfully created.'} format.json{render action: 'show', status: :created, location: @notification} else format.html{render action: 'notification'} format.json{render json: @notification.errors, status: :unprocessable_entity} end end end def show @notification = Rapns::Gcm::Notification.find(params[:id]) end def history @notifications = Rapns::Gcm::Notification.where(:app_id => @app.id) end def relayPost @notification = Rapns::Gcm::Notification.new(notification_params) @notification.app = @app respond_to do |format| if @notification.save format.json{render action: 'show', status: :created, location: @notification} else format.json{render json: @notification.errors, status: :unproceesable_entry} end end end private def set_app @app = current_user.apps.find_by_name(params[:app_name]) end def notification_params data = params[:rapns_gcm_notification][:data] params[:rapns_gcm_notification][:data] = {:message=>data} params[:rapns_gcm_notification] end end
# You will write a method only_unique_elements that takes in an Array # The method returns a new array where all duplicate elements are removed. # You must solve this using a hash. def only_unique_elements(arr) newHash = Hash.new(0) arr.each{|x|newHash[x]=1} newHash.to_a.flatten().select{|x|x.is_a?(String)==true} end print only_unique_elements(['a', 'b', 'a', 'a', 'b', 'c']) == ["a", "b", "c"] puts print only_unique_elements(['cow', 'goat', 'sheep', 'cow', 'cow', 'sheep']) == ["cow", "goat", "sheep"] puts # def only_unique_elements(arr) # Write your code here # frequency = {} # arr.each do |el| # frequency[el] ||= 0 # frequency[el] += 1 # end # frequency.select { |char, num| num == 1 } # return frequency.keys # frequency = {} # arr.each { |ele| frequency[ele] = true } # return frequency.keys # end
require 'rails_helper' RSpec.describe Item, type: :model do it { should belong_to(:section) } it { should have_many(:favorites) } it { should have_many(:users).through(:favorites) } end
require "./test/test_helper" class TeamRepoTest < MiniTest::Test def setup @team_repo = TeamRepo.new('./data/team_info.csv') end def test_team_repo_exists assert_instance_of TeamRepo, @team_repo end def test_team_repo_has_teams assert_equal 33, @team_repo.repo.count end end
require 'minitest/autorun' require 'minitest/rg' # require_relative '../bus' require_relative '../person' require_relative '../bus_stop' class TestBusStop < MiniTest::Test def setup @bus_stop = BusStop.new('Lothian Road') @passenger = Person.new('Stuart', 41) end def test_name assert_equal('Lothian Road', @bus_stop.get_name) end def test_queue_empty assert_equal([], @bus_stop.get_queue) end def test_add_person @bus_stop.add_person(@passenger) assert_equal([@passenger], @bus_stop.get_queue) end end
describe SyntaxHighlighting::Pattern do let(:contents) do { "begin" => "begin_value", "end" => "end_value", "beginCaptures" => { "0" => { "name" => "begin_captures_value" } }, "endCaptures" => { "0" => { "name" => "end_captures_value" } }, "contentName" => "content_name_value", "name" => "name_value", "captures" => { "0" => { "name" => "captures_value" } }, "match" => "match_value", "repository" => { "banana" => { "name" => "banana_name_value" } } } end let(:described_instance) { SyntaxHighlighting::Pattern.new(contents) } describe ".find_or_initialize" do let(:repository) { double(:repository) } subject { described_class.find_or_initialize(contents, repository) } it { is_expected.to be_a(SyntaxHighlighting::Pattern) } it "initializes with the same arguments" do new_pattern = double(:new_pattern) expect(described_class) .to receive(:new) .with(contents, repository) .and_return(new_pattern) expect(subject).to eq(new_pattern) end context "when the pattern is a reference to another" do let(:contents) { { "include" => "banana" } } it "returns the pattern it references" do referenced_pattern = double(:referenced_pattern) expect(repository) .to receive(:get) .with("banana") .and_return(referenced_pattern) expect(subject).to eq(referenced_pattern) end end end describe "#begin" do subject { described_instance.begin } it { is_expected.to eq(/begin_value/) } end describe "#end" do subject { described_instance.end } it { is_expected.to eq(/end_value/) } end describe "#begin_captures" do subject { described_instance.begin_captures } it { is_expected.to be_a(SyntaxHighlighting::Captures) } it "contains the captures" do expect(subject[0]).to eq(:begin_captures_value) end end describe "#end_captures" do subject { described_instance.end_captures } it { is_expected.to be_a(SyntaxHighlighting::Captures) } it "contains the captures" do expect(subject[0]).to eq(:end_captures_value) end end describe "#content_name" do subject { described_instance.content_name } it { is_expected.to eq("content_name_value") } end describe "#name" do subject { described_instance.name } it { is_expected.to eq(:name_value) } end describe "#captures" do subject { described_instance.captures } it { is_expected.to be_a(SyntaxHighlighting::Captures) } it "contains the captures" do expect(subject[0]).to eq(:captures_value) end end describe "#match" do subject { described_instance.match } it { is_expected.to eq(/match_value/) } end describe "#repository" do subject { described_instance.repository } it { is_expected.to be_a(SyntaxHighlighting::Repository) } it "contains the child patterns" do expect(subject.get("#banana")).to be_a(SyntaxHighlighting::Pattern) expect(subject.get("#banana").name).to eq(:banana_name_value) end end describe "#inspect" do subject { described_instance.inspect } it { is_expected.to be_a(String) } end describe "#patterns" do subject { described_instance.patterns } # Seems some languages should support children on `match` too, but for now # is unhandled. context "on a pattern that can have children" do before do contents.delete("match") contents["patterns"] = [ { "name" => "child1" }, { "name" => "child2" } ] end it { is_expected.to be_an(Array) } it { is_expected.to all(be_a(SyntaxHighlighting::Pattern)) } end end end
class Ship attr_reader :member_cells def initialize @sunk = false @member_cells = [] end def sunk? @sunk end def sink! @sunk = true end def cell_count member_cells.count end def accept_cells(cell) member_cells << cell end def are_all_my_cells_hit? sink! if member_cells.all? { |cell| cell.has_been_hit == true} end end
require_relative "live/state_view" require_relative "live/game_policy" require_relative "live/game_engine" require_relative "live/states_history" require_relative "live/file_reader" class LiveController def initialize @view = Live::StateView.new @policy = Live::GamePolicy.new @game_engine = Live::GameEngine.new @history = Live::StatesHistory.new @file_reader = Live::FileReader.new end def call(file_name) current_state = @file_reader.read_file(file_name) loop do @history.push(current_state) system "clear" puts @view.render(current_state) @policy.wait current_state = @game_engine.generate_next_state(current_state) break if @history.include?(current_state) end end end LiveController.new.call("./example.txt")
# Teapot v2.2.0 configuration generated at 2017-10-07 23:42:48 +1300 required_version "2.0" # Project Metadata define_project "botan" do |project| project.title = "Botan" project.summary = 'A cryptography library providing TLS/DTLS, PKIX certificate handling, PKCS#11 and TPM hardware support, password hashing, and post quantum crypto schemes.' project.license = 'Simplified BSD License' end # Build Targets define_target 'botan-library' do |target| target.build do source_files = Files::Directory.join(target.package.path, "upstream") cache_prefix = environment[:build_prefix] / environment.checksum + "botan" package_files = environment[:install_prefix] / "lib/libbotan-2.a" copy source: source_files, prefix: cache_prefix configure prefix: cache_prefix do run! "./configure.py", "--prefix=#{environment[:install_prefix]}", "--cc-bin=#{environment[:cxx]}", "--cc-abi-flags=#{environment[:cxxflags].join(' ')}", "--disable-shared", *environment[:configure], chdir: cache_prefix end make prefix: cache_prefix, package_files: package_files end target.depends 'Build/Files' target.depends 'Build/Clang' target.depends "Build/Make", private: true target.depends :platform target.depends 'Language/C++11', private: true target.provides 'Library/botan' do append linkflags [ ->{install_prefix + 'lib/libbotan-2.a'}, ] end end # Configurations define_configuration 'development' do |configuration| configuration[:source] = "https://github.com/kurocha" configuration.import "botan" # Provides all the build related infrastructure: configuration.require 'platforms' configuration.require 'build-make' configuration.require "generate-project" configuration.require "generate-travis" end define_configuration "botan" do |configuration| configuration.public! configuration.require 'build-make' end
require 'rails_helper' RSpec.describe User, type: :model do context 'validation tests' do it 'ensures email is present' do user = User.new(admin: false).save expect(user).to eq(false) end end end
class Customer include Mongoid::Document field :application, type: String field :application_id, type: String field :email, type: String field :token, type: String field :bypass, type: Boolean embeds_many :bypasses def self.find_or_create application, application_id, email, token, ip customer = find_first application, application_id, email if customer.nil? customer = create application, application_id, email, token end customer.bypasses << Bypass.new({ip: ip, datetime: DateTime.now}) customer end def self.find_first application, application_id, email customers = Customer.where(:application => application).where(:application_id => application_id).where(:email => email) customers[0] end def self.create application, application_id, email, token Customer.create!(:application => application, :application_id => application_id, :email => email, :token => token, :bypass => true) end end
require 'uri' class ShortUrlApi < Grape::API content_type :json, 'application/json' format :json desc '短链详情列表' params do # requires :password, type: String, module: Md5, desc: '采用密码' optional :page, type: Integer, default: 1 optional :per, type: Integer, default: 10 end get '/u' do params[:page] = 1 if params[:page] <= 0 params[:per] = 10 if params[:per] <= 0 skip_num = (params[:page]-1) * params[:per] _sus = ShortUrl.order(created_at: -1).skip(skip_num).limit(params[:per]) { count: ShortUrl.count, short_url_list: _sus.map(&:show) } end desc '生成短链,为了方便使用' params do requires :url, type: String, desc: '原始长链' optional :set_short_url, type: String, desc: '希望的短链接' end post '/u' do unless params[:set_short_url].blank? params[:set_short_url] = params[:set_short_url].downcase error!('短链接长度不能超过8位', 401) if params[:set_short_url].length > 8 %w{w x y z}.each do |char| error!('短链接不能包含 w,x,y,z', 401) if params[:set_short_url].include? char end _short_url = ShortUrl.where(key: params[:set_short_url], key_length: params[:set_short_url].length).first error!('此短链接以被使用', 401) if _short_url && !CAN_COVER end error!('请填入正确的链接,以 http 或 https 开头', 401) unless params[:url] =~ URI::regexp key_url = ShortUrl.create_short_url params[:url], params[:set_short_url] { short_url: key_url } end desc '短链详情' params do requires :key, type: String, desc: '短链key' end get '/u/:key/info' do error!('Not Found', 404) if params[:key].length >8 _short_url = ShortUrl.where(key: params[:key], key_length: params[:key].length).first error!('Not Found', 404) if _short_url.nil? _short_url.show end end
require 'spec_helper' describe Height::Units::Millimeters do describe 'converts to' do before do @millimeters = Height::Units::Millimeters.new(1910) end it 'millimeters' do @millimeters.to_millimeters.should === @millimeters end it 'centimeters' do @millimeters.to_centimeters.should == Height::Units::Centimeters.new(191) end it 'meters' do @millimeters.to_meters.should == Height::Units::Meters.new(1.91) end it 'inches' do @millimeters.to_inches.should == Height::Units::Inches.new(75) end it 'feet' do @millimeters.to_feet.should == Height::Units::Feet.new(6.25) end it 'string' do Height::Units::Millimeters.new(1.6).to_s.should == '2' Height::Units::Millimeters.new(1.0).to_s.should == '1' end end it 'rounds the value to 0 digit precision' do Height::Units::Millimeters.new(1914.5).value.should == 1915 end end
#!/usr/bin/env ruby require "bundler/setup" require "emconvert/version" require "emconvert/converter" require 'optparse' require 'fileutils' options = {:verbose => false, :backup => true} parser = OptionParser.new do|opts| opts.banner = "Usage: emconvert --verbose --backup files" opts.on('-v', '--verbose', 'Show verbose output') do |verbose| options[:verbose] = true; end opts.on('-b', '--backup', 'Create backup files when changed') do |verbose| options[:backup] = true; end opts.on('-h', '--help', 'Displays Help') do puts opts exit end end parser.parse! raise "Need to specify a set of files to process" unless ARGV.length >= 1 ARGV.each do |file| content = File.read(file) puts "Checking file #{file}..." if options[:verbose] converter = Converter.new(content) new_content = converter.convert if new_content != content puts "Found changes..." if options[:verbose] if options[:backup] backup_file = File.join(File.dirname(file),File.basename(file,'.*')) + File.extname(file + '_bak') puts "Creating backup file #{backup_file}..." if options[:verbose] FileUtils.mv(file, backup_file) end File.write(file, new_content) end end
define :outer do _foo = params[:foo] || raise("foo is nil") execute 'outer test' do command "[[ ! -s #{params[:foo]} ]]" # params is in scope, parasm[:foo] has a value end inner 'explicit' do foo _foo # _foo is in scope, so it has a value end inner 'implicit' do foo params[:foo] # params is from a different scope, so params[:foo] has no value end end
module ApplicationHelper def full_title title title.empty? ? t("app_title") : title + " | " + t("app_title") end end
# == Schema Information # # Table name: user_route_relationships # # id :integer not null, primary key # follower_id :integer # route_id :integer # created_at :datetime not null # updated_at :datetime not null # class UserRouteRelationship < ActiveRecord::Base attr_accessible :route_id # user_route_relationships con follower (User model) belongs_to :follower, class_name: 'User' # user_route_relationships con route (Route model) belongs_to :route, class_name: 'Route' #campi obbligatori della user_route_relationships validates :follower_id, presence: true validates :route_id, presence: true end
require 'test_helper' class GroupsControllerTest < ActionController::TestCase test "can get trending groups" do get :index assert_response :ok end test "can get group page" do get :show, id: 'gumi-appreciation-group' assert_response :ok assert_preloaded 'groups' end test "can get group json" do get :show, format: :json, id: 'gumi-appreciation-group' assert_response :ok assert_equal GroupSerializer.new(groups(:gumi)).to_json, @response.body end test "can create new group" do sign_in users(:josh) post :create, group: {name: 'Sugar Water'} assert_response :created end test "cannot create two groups with the same name" do sign_in users(:josh) post :create, group: {name: 'Sugar Water'} post :create, group: {name: 'Sugar Water'} assert_response :conflict end test "can delete a group if site admin" do sign_in users(:josh) delete :destroy, id: 'gumi-appreciation-group' assert_response :ok end test "cannot delete a group if not site admin" do sign_in users(:vikhyat) delete :destroy, id: 'gumi-appreciation-group' assert_response 403 end test "can edit a group if admin" do sign_in users(:vikhyat) put :update, id: 'gumi-appreciation-group', group: { bio: 'Mini bio', about: 'Longer about section' } assert_response :ok end end
require 'rails_helper' describe 'atronaut index' do it 'user can see all astronauts' do astronaut_1 = Astronaut.create(name: 'John Glenn', job: 'engineer', age: 50) astronaut_2 = Astronaut.create(name: 'Buzz Aldren', job: 'conspiract theorist', age: 90) visit '/astronauts' expect(page).to have_content(astronaut_1.name) expect(page).to have_content(astronaut_1.job) expect(page).to have_content("#{astronaut_1.age}") expect(page).to have_content(astronaut_2.name) expect(page).to have_content(astronaut_2.job) expect(page).to have_content("#{astronaut_2.age}") end end
class Profile < ActiveRecord::Base belongs_to :user has_many :taggings, :as => :taggable has_many :tags, :through => :taggings validates_presence_of :name, :surname end
# frozen_string_literal: true module ErrorsCatcher extend ActiveSupport::Concern included do rescue_from ApiAuthentication::Errors::Auth::InvalidCredentials, with: :unauthorized_request rescue_from ApiAuthentication::Errors::Token::Missing, with: :unauthorized_request rescue_from ApiAuthentication::Errors::Token::Invalid, with: :unauthorized_request end private def unauthorized_request(error) json_error_response(error.message, :unauthorized) end end
class Country < ActiveRecord::Base has_many :states accepts_nested_attributes_for :states has_many :permitted_destinations has_many :products, through: :permitted_destinations has_many :default_permitted_destinations has_many :users, through: :default_permitted_destinations def country_name "#{common_name}" end end
require 'json' module Actions module GladiatorsActions def generate_actions(data, actions) data.each do |k, v| if v.is_a?(Hash) v.each do |k, v| if k == "name" define_method ("greeting") do p "Going to death #{v}, salute you!" end elsif k == "weapon" v.each do |v| actions.each_pair do|action, way| define_method ("#{action}_vis_#{v}") do way.call(v) end end end end end end end end end def self.included(base) base.extend(GladiatorsActions) end end RESPONSE = '{"gladiator":{"personal_data":{"name": "Staros", "gender":"male", "age":27}, "skills":["swordsman","spearman","bowmen"], "amunition":{"weapon":["trident","net","dagger"], "armor":[{"head":"no","torso":"belt","limbs":"braser"}] }}}' response = JSON.parse(RESPONSE) Gladiator = Struct.new(*response["gladiator"].keys.collect(&:to_sym)) do def how_old? p "His age is #{personal_data["age"]}" end def spearman? p "Our gladiadiator #{skills.select{|x| x== "spearman" }[0]}! He will make a good retiarius" end def have_weapon? weapon = "no" amunition.each{|x| Hash[*x].each_pair{|key, value| if key == "weapon" then weapon=value end}} p "Glagiator #{personal_data["name"]} is carrying a #{weapon.join(", ")}" end end Gladiator.class_eval do include Actions trident_actions = {:attack => Proc.new{ |weapon| p "Strike #{weapon} in face"}, :defance => Proc.new{ |weapon| p "Block #{weapon} weapon of the opponent"}, :fint => Proc.new{ |weapon| p "Apply #{weapon} feint"} } generate_actions(response["gladiator"], trident_actions) end person = Gladiator.new(*response["gladiator"].values) print "\n" p p person.public_methods(false) print "\n" print "\n" person.how_old? person.spearman? person.have_weapon? print "\n" p "======== Gladiator enters the arena ========" print "\n" person.greeting print "\n" p "======== Lets fight!!!!!!!!!!!!!!!! ========" person.fint_vis_trident person.defance_vis_net person.attack_vis_dagger
# frozen_string_literal: true require_relative 'test_helper' module Dynflow module SemaphoresTest describe ::Dynflow::Semaphores::Stateful do let(:semaphore_class) { ::Dynflow::Semaphores::Stateful } let(:tickets_count) { 5 } it 'can be used as counter' do expected_state = { :tickets => tickets_count, :free => 4, :meta => {} } semaphore = semaphore_class.new(tickets_count) _(semaphore.tickets).must_equal tickets_count _(semaphore.free).must_equal tickets_count _(semaphore.waiting).must_be_empty _(semaphore.get).must_equal 1 _(semaphore.free).must_equal tickets_count - 1 _(semaphore.get(3)).must_equal 3 _(semaphore.free).must_equal tickets_count - (3 + 1) _(semaphore.drain).must_equal 1 _(semaphore.free).must_equal tickets_count - (3 + 1 + 1) semaphore.release _(semaphore.free).must_equal tickets_count - (3 + 1) semaphore.release 3 _(semaphore.free).must_equal tickets_count - 1 _(semaphore.to_hash).must_equal expected_state end it 'can have things waiting on it' do semaphore = semaphore_class.new 1 allowed = semaphore.wait(1) _(allowed).must_equal true _(semaphore.free).must_equal 0 allowed = semaphore.wait(2) _(allowed).must_equal false allowed = semaphore.wait(3) _(allowed).must_equal false waiting = semaphore.get_waiting _(waiting).must_equal 2 waiting = semaphore.get_waiting _(waiting).must_equal 3 end end describe ::Dynflow::Semaphores::Dummy do let(:semaphore_class) { ::Dynflow::Semaphores::Dummy } it 'always has free' do semaphore = semaphore_class.new _(semaphore.free).must_equal 1 _(semaphore.get(5)).must_equal 5 _(semaphore.free).must_equal 1 end it 'cannot have things waiting on it' do semaphore = semaphore_class.new _(semaphore.wait(1)).must_equal true _(semaphore.has_waiting?).must_equal false end end describe ::Dynflow::Semaphores::Aggregating do let(:semaphore_class) { ::Dynflow::Semaphores::Aggregating } let(:child_class) { ::Dynflow::Semaphores::Stateful } let(:children) do { :child_A => child_class.new(3), :child_B => child_class.new(2) } end def assert_semaphore_state(semaphore, state_A, state_B) _(semaphore.children[:child_A].free).must_equal state_A _(semaphore.children[:child_B].free).must_equal state_B _(semaphore.free).must_equal [state_A, state_B].min end it 'can be used as counter' do semaphore = semaphore_class.new(children) assert_semaphore_state semaphore, 3, 2 _(semaphore.get).must_equal 1 assert_semaphore_state semaphore, 2, 1 _(semaphore.get).must_equal 1 assert_semaphore_state semaphore, 1, 0 _(semaphore.get).must_equal 0 assert_semaphore_state semaphore, 1, 0 semaphore.release assert_semaphore_state semaphore, 2, 1 semaphore.release(1, :child_B) assert_semaphore_state semaphore, 2, 2 _(semaphore.drain).must_equal 2 assert_semaphore_state semaphore, 0, 0 end end end end
class ReviewsController < ApplicationController # make @book accessable before_action :find_book before_action :find_review, only: [:edit, :update, :destroy] before_action :authenticate_user!, only: [:new, :edit] def new @review = Review.new end def create @review = Review.new(review_params) # associate review with current book and current user @review.book_id = @book.id @review.user_id = current_user.id if @review.save redirect_to book_path(@book) else render 'new' end end def edit # dont need this line here anymore because the method was defined and called by before_action # @review = Review.find(params[:id]) end def update @review = Review.find(params[:id]) if @review.update(review_params) redirect_to book_path(@book) else render 'edit' end end def destroy @review.destroy redirect_to book_path(@book) end private # require the name which is review, and pass through what will be permitted def review_params params.require(:review).permit(:rating, :comment) end def find_book # finds current book view is associated with based on book_id @book = Book.find(params[:book_id]) end def find_review @review = Review.find(params[:id]) end end
json.array!(@contact_messages) do |contact_message| json.extract! contact_message, :id, :name, :author, :message json.url contact_message_url(contact_message, format: :json) end
feature 'players can enter their names on the screen' do scenario 'inputted names are displayed' do sign_in_and_play expect(page).to have_content("Josue vs. Hannah") end end
# frozen_string_literal: true module Diplomat # Methods for interacting with the Consul ACL Role API endpoint class Role < Diplomat::RestClient @access_methods = %i[list read read_name create delete update] attr_reader :id, :type, :acl # Read ACL role with the given UUID # @param id [String] UUID or name of the ACL role to read # @param options [Hash] options parameter hash # @return [Hash] existing ACL role # rubocop:disable Metrics/PerceivedComplexity def read(id, options = {}, not_found = :reject, found = :return) @options = options custom_params = [] custom_params << use_consistency(options) @raw = send_get_request(@conn_no_err, ["/v1/acl/role/#{id}"], options, custom_params) if @raw.status == 200 && @raw.body.chomp != 'null' case found when :reject raise Diplomat::RoleNotFound, id when :return return parse_body end elsif @raw.status == 404 case not_found when :reject raise Diplomat::RoleNotFound, id when :return return nil end elsif @raw.status == 403 case not_found when :reject raise Diplomat::AclNotFound, id when :return return nil end else raise Diplomat::UnknownStatus, "status #{@raw.status}: #{@raw.body}" end end # rubocop:enable Metrics/PerceivedComplexity # Read ACL role with the given name # @param name [String] name of the ACL role to read # @param options [Hash] options parameter hash # @return [Hash] existing ACL role # rubocop:disable Metrics/PerceivedComplexity def read_name(name, options = {}, not_found = :reject, found = :return) @options = options custom_params = [] custom_params << use_consistency(options) @raw = send_get_request(@conn_no_err, ["/v1/acl/role/name/#{name}"], options, custom_params) if @raw.status == 200 && @raw.body.chomp != 'null' case found when :reject raise Diplomat::RoleNotFound, name when :return return parse_body end elsif @raw.status == 404 case not_found when :reject raise Diplomat::RoleNotFound, name when :return return nil end elsif @raw.status == 403 case not_found when :reject raise Diplomat::AclNotFound, name when :return return nil end else raise Diplomat::UnknownStatus, "status #{@raw.status}: #{@raw.body}" end end # rubocop:enable Metrics/PerceivedComplexity # List all the ACL roles # @param options [Hash] options parameter hash # @return [List] list of [Hash] of ACL roles def list(options = {}) @raw = send_get_request(@conn_no_err, ['/v1/acl/roles'], options) raise Diplomat::AclNotFound if @raw.status == 403 parse_body end # Update an existing ACL role # @param value [Hash] ACL role definition, ID and Name fields are mandatory # @param options [Hash] options parameter hash # @return [Hash] result ACL role def update(value, options = {}) id = value[:ID] || value['ID'] raise Diplomat::IdParameterRequired if id.nil? role_name = value[:Name] || value['Name'] raise Diplomat::NameParameterRequired if role_name.nil? custom_params = use_cas(@options) @raw = send_put_request(@conn, ["/v1/acl/role/#{id}"], options, value, custom_params) if @raw.status == 200 parse_body elsif @raw.status == 400 raise Diplomat::RoleMalformed, @raw.body else raise Diplomat::UnknownStatus, "status #{@raw.status}: #{@raw.body}" end end # Create a new ACL role # @param value [Hash] ACL role definition, Name field is mandatory # @param options [Hash] options parameter hash # @return [Hash] new ACL role def create(value, options = {}) blacklist = ['ID', 'iD', 'Id', :ID, :iD, :Id] & value.keys raise Diplomat::RoleMalformed, 'ID should not be specified' unless blacklist.empty? id = value[:Name] || value['Name'] raise Diplomat::NameParameterRequired if id.nil? custom_params = use_cas(@options) @raw = send_put_request(@conn, ['/v1/acl/role'], options, value, custom_params) # rubocop:disable Style/GuardClause if @raw.status == 200 return parse_body elsif @raw.status == 500 && @raw.body.chomp.include?('already exists') raise Diplomat::RoleAlreadyExists, @raw.body else raise Diplomat::UnknownStatus, "status #{@raw.status}: #{@raw.body}" end end # rubocop:enable Style/GuardClause # Delete an ACL role by its UUID # @param id [String] UUID of the ACL role to delete # @param options [Hash] options parameter hash # @return [Bool] def delete(id, options = {}) @raw = send_delete_request(@conn, ["/v1/acl/role/#{id}"], options, nil) @raw.body.chomp == 'true' end end end
# == Schema Information # # Table name: tables # # id :uuid not null, primary key # name :string # location :string # splited :boolean default(FALSE) # order_id :uuid # parent_id :uuid # status :integer # created_at :datetime not null # updated_at :datetime not null # class Table < ActiveRecord::Base include Total default_scope { where(parent_id: nil) } has_many :parts, foreign_key: 'parent_id', class_name: 'TableParts' end
class Article < ActiveRecord::Base validates :title, presence:true, length:{minimum:5} validates :content, presence:true, length:{minimum:10} validates :status, presence:true scope :status_active,->{where(status:'Dirilis')} has_many :comments, dependent: :destroy end
require 'rack' require 'active_support' require 'active_support/concern' require 'active_support/core_ext/kernel/reporting' require 'dionysus/string/version_match' module Circuit # Compatibility extensions for Rack 1.3 and Rails 3.1 module Compatibility # Make Rack 1.3 and ActiveSupport 3.1 compatible with circuit. # * Overrides Rack::Builder and Rack::URLMap with the classes from Rack 1.4 # * Adds #demodulize and #deconstantize inflections to ActiveSupport def self.make_compatible rack13 if ::Rack.release.version_match?("~> 1.3.0") active_support31 if ActiveSupport::VERSION::STRING.version_match?("~> 3.1.0") end # Include in a model to modify it for compatibility. module ActiveModel31 extend ActiveSupport::Concern # @!method define_attribute_methods(*args) # Modified to call `attribute_method_suffix ''` first to create the # accessors. # @see http://rubydoc.info/gems/activemodel/ActiveModel/AttributeMethods/ClassMethods#define_attribute_methods-instance_method # @see http://rubydoc.info/gems/activemodel/ActiveModel/AttributeMethods/ClassMethods#attribute_method_suffix-instance_method included do if ActiveModel::VERSION::STRING.version_match?("~> 3.1.0") if has_active_model_module?("AttributeMethods") class << self alias_method_chain :define_attribute_methods, :default_accessor end end end end private module ClassMethods def has_active_model_module?(mod_name) included_modules.detect {|mod| mod.to_s == "ActiveModel::#{mod_name.to_s.camelize}"} end def define_attribute_methods_with_default_accessor(*args) attribute_method_suffix '' define_attribute_methods_without_default_accessor(*args) end end end private def self.vendor_path Circuit.vendor_path end def self.rack13 require "rack/urlmap" require "rack/builder" require vendor_path.join("rack-1.4", "builder").to_s silence_warnings { require vendor_path.join("rack-1.4", "urlmap").to_s } end def self.active_support31 require "active_support/inflector" require vendor_path.join("active_support-3.2", "inflector", "methods").to_s require vendor_path.join("active_support-3.2", "core_ext", "string", "inflections").to_s end end end
# This railtie is for bootstrapping the pawnee gem only # It adds the config/pawnee directory to the loadpath if defined?(Rails) module Pawnee class Railtie < Rails::Railtie initializer "pawnee.configure_rails_initialization" do puts "INITIALIZE1" path = (Rails.root + 'config/pawnee').to_s puts path unless $LOAD_PATH.include?(path) $LOAD_PATH.unshift(path) end puts "Require: pawnee/base" require 'pawnee/base' end end end else require 'pawnee/base' end
require 'spec_helper' require 'json' docs = JSON.parse(File.read('spec/fixtures/cjk_map_solr_fixtures.json')) stanford_docs = JSON.parse(File.read('spec/fixtures/cjk_stanford_fixtures.json')) describe 'CJK character equivalence' do include_context 'solr_helpers' def add_single_field_doc char solr.add({ id: 1, cjk_title: char }) solr.commit end before(:all) do delete_all solr.add(docs) solr.commit end describe 'Direct mapping check' do before(:all) do delete_all solr.add(docs) solr.commit end docs.each do |map| from = map['cjk_mapped_from'] to = map['cjk_mapped_to'] id = map['id'].to_s it "#{from} => #{to}" do expect(solr_resp_doc_ids_only({ 'fq'=>"cjk_mapped_to:#{from}"})).to include(id) end it "#{to} => #{from} (reverse)" do expect(solr_resp_doc_ids_only({ 'fq'=>"cjk_mapped_from:#{to}"})).to include(id) end end end describe 'Stanford direct mapping check' do before(:all) do delete_all solr.add(stanford_docs) solr.commit end stanford_docs.each do |map| from = map['cjk_mapped_from'] to = map['cjk_mapped_to'] id = map['id'].to_s it "#{from} => #{to}" do expect(solr_resp_doc_ids_only({ 'fq'=>"cjk_mapped_to:#{from}"})).to include(id) end it "#{to} => #{from} (reverse)" do expect(solr_resp_doc_ids_only({ 'fq'=>"cjk_mapped_from:#{to}"})).to include(id) end end end describe '4 character variations 壱 => 一, 壹 => 一, 弌 => 一' do it 'indirect mapping 壹 => 壱' do add_single_field_doc('壹') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:壱' })).to include('1') end it 'indirect mapping 壹 => 弌' do add_single_field_doc('弌') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:壹' })).to include('1') end it 'indirect mapping 壱 => 弌' do add_single_field_doc('壱') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:弌' })).to include('1') end end describe 'multi-character searches' do describe "Chinese" do it '毛沢東思想 => 毛泽东思想' do add_single_field_doc('毛沢東思想') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"毛泽东思想"' })).to include('1') end it 'can find this particular title' do titles = [ '長沙走馬楼三國吴简 / 長沙市文物考古研究所, 中國文物研究所, 北京大學歷史學系走馬樓簡牘整理組編著.', '走馬楼三國吴简', '嘉禾吏民田家[bie]', '竹簡.' ] add_single_field_doc(titles) params = {qf: 'cjk_title', pf: 'cjk_title', q: '长沙走马楼三国吴简'} expect(solr_resp_doc_ids_only(params)).to include('1') end it "can find notes" do notes = '闲话' solr.add({ id: 1, notes_index: '閑話' }) solr.commit params = {q: notes} expect(solr_resp_doc_ids_only(params, 'search')).to include('1') end end describe "Korean" do it '고려의후삼국통일과후백제 => 고려의 후삼국 통일과 후백제' do add_single_field_doc('고려의후삼국통일과후백제') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"고려의 후삼국 통일과"' })).to include('1') end it '한국사 => 한국' do add_single_field_doc('한국사') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"한국"' })).to include('1') end end describe "Japanese Hiragana" do it 'における => おける' do add_single_field_doc('における') # This works, but not because of cjk_text. It works because of the # standard tokenizer on the text field. expect(solr_resp_doc_ids_only({ 'q'=>'おける' })).to include('1') end end end describe 'punctuation marks are stripped' do it '『「「「想』」」」 => 」」想「「' do add_single_field_doc('『「「「想』」」」') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"」」想「「"' })).to include('1') end end describe 'cjk "0"' do it '二〇〇〇 => 二000' do add_single_field_doc('二000') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"二〇〇〇"' })).to include('1') end it '二000 => 二〇〇〇' do add_single_field_doc('二〇〇〇') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"二000"' })).to include('1') end end describe 'mappings covered by other solr analyzers' do it '亜梅亜 => 亞梅亞' do add_single_field_doc('亜梅亜') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"亞梅亞"' })).to include('1') end it '亞梅亞 => 亜梅亜' do add_single_field_doc('亞梅亞') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"亜梅亜"' })).to include('1') end it '梅亜 => 梅亞' do add_single_field_doc('梅亜') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"梅亞"' })).to include('1') end it '梅亜 => 梅亞' do add_single_field_doc('梅亞') expect(solr_resp_doc_ids_only({ 'fq'=>'cjk_title:"梅亜"' })).to include('1') end end describe 'mapping applied to search fields' do def qf_pf_params q, field {qf: "${#{field}_qf}", pf: "${#{field}_pf}", q: q} end it '国史大辞典 => 國史大辭典 left anchor' do solr.add({ id: 1, title_la: '國史大辭典' }) solr.commit expect(solr_resp_doc_ids_only(qf_pf_params("国史大辞典","left_anchor"))).to include('1') end it '三晋出版社 => 三晉出版社 publisher' do solr.add({ id: 1, pub_created_vern_display: '三晋出版社' }) solr.commit expect(solr_resp_doc_ids_only(qf_pf_params("三晉出版社", "publisher"))).to include('1') end it '巴蜀書社 => 巴蜀书社 notes' do solr.add({ id: 1, cjk_notes: '巴蜀書社' }) solr.commit expect(solr_resp_doc_ids_only(qf_pf_params("巴蜀书社 ", "notes"))).to include('1') end it '鳳凰出版社 => 凤凰出版社 series title' do solr.add({ id: 1, cjk_series_title: '鳳凰出版社' }) solr.commit expect(solr_resp_doc_ids_only(qf_pf_params("凤凰出版社 ", "series_title"))).to include('1') end end after(:all) do delete_all end end
$LOAD_PATH.unshift File.dirname(__FILE__) require 'smtpapi/version' require 'json' module Smtpapi # # SendGrid smtpapi header implementation # class Header attr_reader :to, :sub, :section, :category, :unique_args, :filters attr_reader :send_at, :send_each_at, :asm_group_id, :ip_pool def initialize @to = [] @sub = {} @section = {} @category = [] @unique_args = {} @filters = {} @send_at = nil @send_each_at = [] @asm_group_id = nil @ip_pool = nil end def add_to(address, name = nil) if address.is_a?(Array) @to.concat(address) else value = address value = "#{name} <#{address}>" unless name.nil? @to.push(value) end self end def set_tos(addresses) @to = addresses self end def add_substitution(sub, values) @sub[sub] = values self end def set_substitutions(key_value_pairs) @sub = key_value_pairs self end def add_section(key, value) @section[key] = value self end def set_sections(key_value_pairs) @section = key_value_pairs self end def add_unique_arg(key, value) @unique_args[key] = value self end def set_unique_args(key_value_pairs) @unique_args = key_value_pairs self end def add_category(category) @category.push(category) self end def set_categories(categories) @category = categories self end def add_filter(filter_name, parameter_name, parameter_value) @filters[filter_name] = {} if @filters[filter_name].nil? @filters[filter_name]['settings'] = {} if @filters[filter_name]['settings'].nil? @filters[filter_name]['settings'][parameter_name] = parameter_value self end def set_filters(filters) @filters = filters self end def set_send_at(send_at) @send_at = send_at self end def set_send_each_at(send_each_at) @send_each_at = send_each_at self end def set_asm_group(group_id) @asm_group_id = group_id self end def set_ip_pool(pool_name) @ip_pool = pool_name self end def json_string escape_unicode(to_array.to_json) end alias_method :to_json, :json_string def escape_unicode(str) str.unpack('U*').map do |i| if i > 65_535 "\\u#{format('%04x', ((i - 0x10000) / 0x400 + 0xD800))}" \ "\\u#{format('%04x', ((i - 0x10000) % 0x400 + 0xDC00))}" elsif i > 127 "\\u#{format('%04x', i)}" else i.chr('UTF-8') end end.join end protected def to_array data = {} data['to'] = @to unless @to.empty? data['sub'] = @sub unless @sub.empty? data['section'] = @section unless @section.empty? data['unique_args'] = @unique_args unless @unique_args.empty? data['category'] = @category unless @category.empty? data['filters'] = @filters unless @filters.empty? data['send_at'] = @send_at.to_i unless @send_at.nil? data['asm_group_id'] = @asm_group_id.to_i unless @asm_group_id.nil? data['ip_pool'] = @ip_pool unless @ip_pool.nil? str_each_at = [] @send_each_at.each do |val| str_each_at.push(val.to_i) end data['send_each_at'] = str_each_at unless str_each_at.empty? data end end end
class CreatePhotos < ActiveRecord::Migration def change create_table :photos do |t| t.string :user_id t.string :uid t.string :caption t.string :name t.string :url t.datetime :taken_at t.integer :likes t.timestamps end add_index :photos, :user_id add_index :photos, :uid end end
class Func module InitIvars def initialize(*args, &block) params = Params.new method(:initialize) if block && !params.block? raise ArgumentError, "#{self.class}#initialize does not accept a block" end kwargs = args.pop if params.keys? params.each_with_arg_index do |name, index| value = case index when Numeric, Range then args[index] when Symbol then kwargs.fetch(index) else block end instance_variable_set("@#{name}", value) end end class Params def initialize(method) @params = method.parameters end def each_with_arg_index negative_index = nil @params.each_with_index do |(type, name), i| arg_index = case type when :block nil when :rest negative_index = -1 - reqs_after_rest i..negative_index when :opt, :req if negative_index negative_index += 1 else i end else # kwarg name end yield name, arg_index end end def keys? @params.any? { |(type, _)| [:key, :keyreq].include? type } end def block? type, _ = @params.last type == :block end private def reqs_after_rest count = nil @params.each do |(type, _), i| if count.nil? count = 0 if type == :rest elsif type == :req count += 1 else break end end count end end end end
# encoding: US-ASCII require 'stringio' require 'binary_struct' require 'miq_unicode' # //////////////////////////////////////////////////////////////////////////// # // Data definitions. # TODO: reserved1 is the infamous magic number. Somehow it works to preserve # case on Windows XP. Nobody seems to know how. Here it is always set to 0 # (which yields uppercase names on XP). module Fat32 using ManageIQ::UnicodeString DIR_ENT_SFN = BinaryStruct.new([ 'a11', 'name', # If name[0] = 0, unallocated; if name[0] = 0xe5, deleted. DOES NOT INCLUDE DOT. 'C', 'attributes', # See FA_ below. If 0x0f then LFN entry. 'C', 'reserved1', # Reserved. 'C', 'ctime_tos', # Created time, tenths of second. 'S', 'ctime_hms', # Created time, hours, minutes & seconds. 'S', 'ctime_day', # Created day. 'S', 'atime_day', # Accessed day. 'S', 'first_clus_hi', # Hi 16-bits of first cluster address. 'S', 'mtime_hms', # Modified time, hours, minutes & seconds. 'S', 'mtime_day', # Modified day. 'S', 'first_clus_lo', # Lo 16-bits of first cluster address. 'L', 'file_size', # Size of file (0 for directories). ]) DIR_ENT_LFN = BinaryStruct.new([ 'C', 'seq_num', # Sequence number, bit 6 marks end, 0xe5 if deleted. 'a10', 'name', # UNICODE chars 1-5 of name. 'C', 'attributes', # Always 0x0f. 'C', 'reserved1', # Reserved. 'C', 'checksum', # Checksum of SFN entry, all LFN entries must match. 'a12', 'name2', # UNICODE chars 6-11 of name. 'S', 'reserved2', # Reserved. 'a4', 'name3' # UNICODE chars 12-13 of name. ]) CHARS_PER_LFN = 13 LFN_NAME_MAXLEN = 260 DIR_ENT_SIZE = 32 ATTRIB_OFFSET = 11 # //////////////////////////////////////////////////////////////////////////// # // Class. class DirectoryEntry # From the UTF-8 perspective. # LFN name components: entry hash name, char offset, length. LFN_NAME_COMPONENTS = [ ['name', 0, 5], ['name2', 5, 6], ['name3', 11, 2] ] # Name component second sub access names. LFN_NC_HASHNAME = 0 LFN_NC_OFFSET = 1 LFN_NC_LENGTH = 2 # SFN failure cases. SFN_NAME_LENGTH = 1 SFN_EXT_LENGTH = 2 SFN_NAME_NULL = 3 SFN_NAME_DEVICE = 4 SFN_ILLEGAL_CHARS = 5 # LFN failure cases. LFN_NAME_LENGTH = 1 LFN_NAME_DEVICE = 2 LFN_ILLEGAL_CHARS = 3 # FileAttributes FA_READONLY = 0x01 FA_HIDDEN = 0x02 FA_SYSTEM = 0x04 FA_LABEL = 0x08 FA_DIRECTORY = 0x10 FA_ARCHIVE = 0x20 FA_LFN = 0x0f # DOS time masks. MSK_DAY = 0x001f # Range: 1 - 31 MSK_MONTH = 0x01e0 # Right shift 5, Range: 1 - 12 MSK_YEAR = 0xfe00 # Right shift 9, Range: 127 (add 1980 for year). MSK_SEC = 0x001f # Range: 0 - 29 WARNING: 2 second granularity on this. MSK_MIN = 0x07e0 # Right shift 5, Range: 0 - 59 MSK_HOUR = 0xf800 # Right shift 11, Range: 0 - 23 # AllocationFlags AF_NOT_ALLOCATED = 0x00 AF_DELETED = 0xe5 AF_LFN_LAST = 0x40 # Members. attr_reader :unused, :name, :dirty attr_accessor :parentCluster, :parentOffset # NOTE: Directory is responsible for setting parent. # These describe the cluster & offset of the START of the directory entry. # Initialization def initialize(buf = nil) # Create for write. if buf == nil self.create return end # Handle possibly multiple LFN records. data = StringIO.new(buf); @lfn_ents = [] checksum = 0; @name = "" loop do buf = data.read(DIR_ENT_SIZE) if buf == nil @unused = "" return end # If attribute contains 0x0f then LFN entry. isLfn = buf[ATTRIB_OFFSET] == FA_LFN @dir_ent = isLfn ? DIR_ENT_LFN.decode(buf) : DIR_ENT_SFN.decode(buf) break if !isLfn # Ignore this entry if deleted or not allocated. af = @dir_ent['seq_num'] if af == AF_DELETED || af == AF_NOT_ALLOCATED @name = @dir_ent['seq_num'] @unused = data.read() return end # Set checksum or make sure it's the same checksum = @dir_ent['checksum'] if checksum == 0 raise "Directory entry LFN checksum mismatch." if @dir_ent['checksum'] != checksum # Track LFN entry, gather names & prepend to name. @lfn_ents << @dir_ent @name = getLongNameFromEntry(@dir_ent) + @name end #LFN loop # Push the rest of the data back. @unused = data.read() # If this is the last record of an LFN chain, check the checksum. if checksum != 0 csum = calcChecksum if csum != checksum puts "Directory entry SFN checksum does not match LFN entries:" puts "Got 0x#{'%02x' % csum}, should be 0x#{'%02x' % checksum}." puts "Non LFN OS corruption?" puts dump raise "Checksum error" end end # Populate name if not LFN. if @name == "" && !@dir_ent['name'].empty? @name = @dir_ent['name'][0, 8].strip ext = @dir_ent['name'][8, 3].strip @name += "." + ext unless ext.empty? end end # //////////////////////////////////////////////////////////////////////////// # // Class helpers & accessors. # Return this entry as a raw string. def raw out = "" @lfn_ents.each {|ent| out += BinaryStruct.encode(ent, DIR_ENT_LFN)} if @lfn_ents out += BinaryStruct.encode(@dir_ent, DIR_ENT_SFN) end # Number of dir ent structures (both sfn and lfn). def numEnts num = 1 num += @lfn_ents.size if @lfn_ents return num end # Return normalized 8.3 name. def shortName name = @dir_ent['name'][0, 8].strip ext = @dir_ent['name'][8, 3].strip name += "." + ext if ext != "" return name end # Construct & return long name from lfn entries. def longName return nil if @lfn_ents == nil name = "" @lfn_ents.reverse.each {|ent| name += getLongNameFromEntry(ent)} return name end # WRITE: change filename. def name=(filename) @dirty = true # dot and double dot are special cases (no processing please). if filename != "." and filename != ".." if filename.size > 12 || (not filename.include?(".") && filename.size > 8) mkLongName(filename) @name = self.longName else @dir_ent['name'] = mkSfn(filename) @name = self.shortName end else @dir_ent['name']= filename.ljust(11) @name = filename end end # WRITE: change magic number. def magic=(magic) @dirty = true @dir_ent['reserved1'] = magic end def magic return @dir_ent['reserved1'] end # WRITE: change attribs. def setAttribute(attrib, set = true) @dirty = true if set @dir_ent['attributes'] |= attrib else @dir_ent['attributes'] &= (~attrib) end end # WRITE: change length. def length=(len) @dirty = true @dir_ent['file_size'] = len end # WRITE: change first cluster. def firstCluster=(first_clus) @dirty = true @dir_ent['first_clus_hi'] = (first_clus >> 16) @dir_ent['first_clus_lo'] = (first_clus & 0xffff) end # WRITE: change access time. def aTime=(tim) @dirty = true time, day = rubyToDosTime(tim) @dir_ent['atime_day'] = day end # To support root dir times (all zero). def zeroTime @dirty = true @dir_ent['atime_day'] = 0 @dir_ent['ctime_tos'] = 0; @dir_ent['ctime_hms'] = 0; @dir_ent['ctime_day'] = 0 @dir_ent['mtime_hms'] = 0; @dir_ent['mtime_day'] = 0 end # WRITE: change modified (written) time. def mTime=(tim) @dirty = true @dir_ent['mtime_hms'], @dir_ent['mtime_day'] = rubyToDosTime(tim) end # WRITE: write or rewrite directory entry. def writeEntry(bs) return if not @dirty cluster = @parentCluster; offset = @parentOffset buf = bs.getCluster(cluster) if @lfn_ents @lfn_ents.each {|ent| buf[offset...(offset + DIR_ENT_SIZE)] = BinaryStruct.encode(ent, DIR_ENT_LFN) offset += DIR_ENT_SIZE if offset >= bs.bytesPerCluster bs.putCluster(cluster, buf) cluster, buf = bs.getNextCluster(cluster) offset = 0 end } end buf[offset...(offset + DIR_ENT_SIZE)] = BinaryStruct.encode(@dir_ent, DIR_ENT_SFN) bs.putCluster(cluster, buf) @dirty = false end # WRITE: delete file. def delete(bs) # Deallocate data chain. bs.wipeChain(self.firstCluster) if self.firstCluster != 0 # Deallocate dir entry. if @lfn_ents then @lfn_ents.each {|ent| ent['seq_num'] = AF_DELETED} end @dir_ent['name'][0] = AF_DELETED @dirty = true self.writeEntry(bs) end def close(bs) writeEntry(bs) if @dirty end def attributes return @dir_ent['attributes'] end def length return @dir_ent['file_size'] end def firstCluster return (@dir_ent['first_clus_hi'] << 16) + @dir_ent['first_clus_lo'] end def isDir? return true if @dir_ent['attributes'] & FA_DIRECTORY == FA_DIRECTORY return false end def mTime return dosToRubyTime(@dir_ent['mtime_day'], @dir_ent['mtime_hms']) end def aTime return dosToRubyTime(@dir_ent['atime_day'], 0) end def cTime return dosToRubyTime(@dir_ent['ctime_day'], @dir_ent['ctime_hms']) end # //////////////////////////////////////////////////////////////////////////// # // Utility functions. def getLongNameFromEntry(ent) pre_name = ""; hashNames = %w(name name2 name3) hashNames.each {|name| n = ent["#{name}"] # Regexp.new options used below: # nil (default options: not case insensitive, extended, multiline, etc.) # 'n' - No encoding on the regexp regex = Regexp.new('\377', nil, 'n') pre_name += n.gsub(regex, "").UnicodeToUtf8.gsub(/\000/, "") } return pre_name end def incShortName @dirty = true num = @dir_ent['name'][7].to_i num += 1 raise "More than 9 files with name: #{@dir_ent['name'][0, 6]}" if num > 57 @dir_ent['name'][7] = num csum = calcChecksum() if @lfn_ents @lfn_ents.each {|ent| ent['checksum'] = csum} end end def create @dirty = true @dir_ent = Hash.new @dir_ent['name'] = "FILENAMEEXT" @name = self.shortName @dir_ent['attributes'] = FA_ARCHIVE @dir_ent['ctime_tos'] = 0 @dir_ent['ctime_hms'], @dir_ent['ctime_day'] = rubyToDosTime(Time.now) @dir_ent['atime_day'] = @dir_ent['ctime_day'] @dir_ent['mtime_hms'], @dir_ent['mtime_day'] = @dir_ent['ctime_hms'], @dir_ent['ctime_day'] # Must fill all members or BinaryStruct.encode fails. self.magic = 0x00; self.length = 0; self.firstCluster = 0 #magic used to be 0x18 end def mkLongName(name) @lfn_ents = mkLfn(name) @dir_ent['name'] = mkSfn(name) # Change magic number to 0. @dir_ent['reserved1'] = 0 # Do checksums in lfn entries. csum = calcChecksum() @lfn_ents.each {|ent| ent['checksum'] = csum} end def mkLfn(name) name = mkLegalLfn(name) lfn_ents = [] # Get number of LFN entries necessary to encode name. ents, leftover = name.length.divmod(CHARS_PER_LFN) if leftover > 0 ents += 1 name += "\000" end # Split out & convert name components. 1.upto(ents) {|ent_num| ent = {}; ent['attributes'] = FA_LFN; ent['seq_num'] = ent_num ent['reserved1'] = 0; ent['reserved2'] = 0; LFN_NAME_COMPONENTS.each {|comp| chStart = (ent_num - 1) * CHARS_PER_LFN + comp[LFN_NC_OFFSET] if chStart > name.length ent["#{comp[LFN_NC_HASHNAME]}"] = "\377".b * (comp[LFN_NC_LENGTH] * 2) else ptName = name[chStart, comp[LFN_NC_LENGTH]] ptName.Utf8ToUnicode! if ptName.length < comp[LFN_NC_LENGTH] * 2 ptName += "\377".b * (comp[LFN_NC_LENGTH] * 2 - ptName.length) end ent["#{comp[LFN_NC_HASHNAME]}"] = ptName end } lfn_ents << ent } lfn_ents.reverse! lfn_ents[0]['seq_num'] |= AF_LFN_LAST return lfn_ents end def mkSfn(name) return mkLegalSfn(name) end def isIllegalSfn(name) # Check: name length, extension length, NULL file name, # device names as file names & illegal chars. return SFN_NAME_LENGTH if name.length > 12 extpos = name.reverse.index(".") return SFN_EXT_LENGTH if extpos > 3 return SFN_NAME_NULL if extpos == 0 fn = name[0...extpos].downcase return SFN_NAME_DEVICE if checkForDeviceNames(fn) return SFN_ILLEGAL_CHARS if name.index(/[;+=\[\]',\"*\\<>\/?\:|]/) != nil return false end def checkForDeviceName(fn) %w[aux com1 com2 com3 com4 lpt lpt1 lpt2 lpt3 lpt4 mailslot nul pipe prn].each {|bad| return true if fn == bad } return false end def mkLegalSfn(name) name = name.upcase; name = name.delete(" ") name = name + "." if not name.include?(".") extpos = name.reverse.index(".") if extpos == 0 then ext = "" else ext = name[-extpos, 3] end fn = name[0, (name.length - extpos - 1)] fn = fn[0, 6] + "~1" if fn.length > 8 return (fn.ljust(8) + ext.ljust(3)).gsub(/[;+=\[\]',\"*\\<>\/?\:|]/, "_") end def isIllegalLfn(name) return LFN_NAME_LENGTH if name.length > LFN_NAME_MAXLEN return LFN_ILLEGAL_CHARS if name.index(/\/\\:><?/) != nil return false end def mkLegalLfn(name) name = name[0...LFN_NAME_MAXLEN] if name.length > LFN_NAME_MAXLEN return name.gsub(/\/\\:><?/, "_") end def calcChecksum name = @dir_ent['name']; csum = 0 0.upto(10) {|i| csum = ((csum & 1 == 1 ? 0x80 : 0) + (csum >> 1) + name[i]) & 0xff } return csum end def dosToRubyTime(dos_day, dos_time) # Extract d,m,y,s,m,h & range check. day = dos_day & MSK_DAY; day = 1 if day == 0 month = (dos_day & MSK_MONTH) >> 5; month = 1 if month == 0 month = month.modulo(12) if month > 12 year = ((dos_day & MSK_YEAR) >> 9) + 1980 #DOS year epoc is 1980. # Extract seconds, range check & expand granularity. sec = (dos_time & MSK_SEC); sec = sec.modulo(29) if sec > 29; sec *= 2 min = (dos_time & MSK_MIN) >> 5; min = min.modulo(59) if min > 59 hour = (dos_time & MSK_HOUR) >> 11; hour = hour.modulo(23) if hour > 23 # Make a Ruby time. return Time.mktime(year, month, day, hour, min, sec) end def rubyToDosTime(tim) # Time sec = tim.sec; sec -= 1 if sec == 60 #correction for possible leap second. sec = (sec / 2).to_i #dos granularity is 2sec. min = tim.min; hour = tim.hour dos_time = (hour << 11) + (min << 5) + sec # Day day = tim.day; month = tim.month # NOTE: This fails after 2107. year = tim.year - 1980 #DOS year epoc is 1980. dos_day = (year << 9) + (month << 5) + day return dos_time, dos_day end # Dump object. def dump out = "\#<#{self.class}:0x#{'%08x' % self.object_id}>\n" if @lfn_ents out += "LFN Entries:\n" @lfn_ents.each {|ent| out += "Sequence num : 0x#{'%02x' % ent['seq_num']}\n" n = ent['name']; n.UnicodeToUtf8! unless n == nil out += "Name1 : '#{n}'\n" out += "Attributes : 0x#{'%02x' % ent['attributes']}\n" out += "Reserved1 : 0x#{'%02x' % ent['reserved1']}\n" out += "Checksum : 0x#{'%02x' % ent['checksum']}\n" n = ent['name2']; n.UnicodeToUtf8! unless n == nil out += "Name2 : '#{n}'\n" out += "Reserved2 : 0x#{'%04x' % ent['reserved2']}\n" n = ent['name3']; n.UnicodeToUtf8! unless n == nil out += "Name3 : '#{n}'\n\n" } end out += "SFN Entry:\n" out += "Name : #{@dir_ent['name']}\n" out += "Attributes : 0x#{'%02x' % @dir_ent['attributes']}\n" out += "Reserved1 : 0x#{'%02x' % @dir_ent['reserved1']}\n" out += "CTime, tenths: 0x#{'%02x' % @dir_ent['ctime_tos']}\n" out += "CTime, hms : 0x#{'%04x' % @dir_ent['ctime_hms']}\n" out += "CTime, day : 0x#{'%04x' % @dir_ent['ctime_day']} (#{cTime})\n" out += "ATime, day : 0x#{'%04x' % @dir_ent['atime_day']} (#{aTime})\n" out += "First clus hi: 0x#{'%04x' % @dir_ent['first_clus_hi']}\n" out += "MTime, hms : 0x#{'%04x' % @dir_ent['mtime_hms']}\n" out += "MTime, day : 0x#{'%04x' % @dir_ent['mtime_day']} (#{mTime})\n" out += "First clus lo: 0x#{'%04x' % @dir_ent['first_clus_lo']}\n" out += "File size : 0x#{'%08x' % @dir_ent['file_size']}\n" end end end # module Fat32
module Yaks class Resource class Form class Field include Yaks::Mapper::Form::Field.attributes.add(error: nil) undef value def value if type.equal? :select selected = options.find(&:selected) selected.value if selected else @value end end def with_value(value) if type.equal? :select with(options: select_options_for_value(value)) else with(value: value) end end private def select_options_for_value(value) unset = ->(option) { option.selected && !value().eql?(value) } set = ->(option) { !option.selected && option.value.eql?(value) } options.each_with_object([]) do |option, new_opts| new_opts << case option when unset option.with selected: false when set option.with selected: true else option end end end end end end end
class Project < ActiveRecord::Base attr_accessible :title has_many :memberships, { dependent: :destroy, inverse_of: :project } has_many :users, { through: :memberships } end
class AddEnglishColumnToGenre < ActiveRecord::Migration def change add_column :genres, :english, :boolean, default: true end end
require './app/simple/basic_calculator_engine' require 'test/unit' require 'test/unit/notify' class BasicCalculatorEngineTest < Test::Unit::TestCase def setup() @calc = BasicCalculatorEngine.new() end def test_accepts_new_number() # Intent revealing name # Arrange num = 25.35 # Act, Assert assert_equal(num, @calc.enter(num), "enter:") # message to easily find where the test breaks assert_equal(num, @calc.result(), "result:") # Reset end def test_should_add() # BDD style name numToAdd1 = 33.23 numToAdd2 = 21.2134 assert_equal(numToAdd1, @calc.add(numToAdd1), "starting from zero") assert_equal(numToAdd1 + numToAdd2, @calc.add(numToAdd2), "cumulative") assert_equal(numToAdd1 + numToAdd2, @calc.result, "stores result") end def test_multiplies() num1 = 3 num2 = 6 @calc.enter(num1) assert_equal(num1 * num2, @calc.multiply(num2), "returns result") assert_equal(num1 * num2, @calc.result, "stores result") end def subtracts end def clears end def divides end def raises_exception_on_division_by_zero end end