text
stringlengths
10
2.61M
class OrderItem < ApplicationRecord belongs_to :order belongs_to :item enum production_status: {着手不可:0, 制作待ち:1, 製作中:2, 製作完了:3 } end
class AddMissionIdToBatiments < ActiveRecord::Migration def change add_column :batiments, :mission_id, :integer end end
module Enjoy::Pages module Models module Blockset extend ActiveSupport::Concern include Enjoy::Model include Enjoy::Enableable include ManualSlug include Enjoy::Pages.orm_specific('Blockset') included do manual_slug :name end def render(view, content = "...
class Card < ApplicationRecord belongs_to :user validates :user_id, :payjp_id, presence: true end
class RenameCommetToComment < ActiveRecord::Migration[5.0] def change rename_table :commets, :comments end end
class RemoveOrderItemIdFromOrders < ActiveRecord::Migration[5.0] def change remove_columns :orders, :order_item_id end end
class ApplicationMailer < ActionMailer::Base default from: "support@joblisting88.com" layout 'mailer' before_action :set_x_smtpapi private def set_x_smtpapi headers 'X-SMTPAPI' => { filters: { templates: { settings: { enable: 1, template_id: '74d9616d-13e5...
class Genre < ApplicationRecord has_and_belongs_to_many :albums before_create do self.name = name.downcase end validates :name, uniqueness: true end
class User < ApplicationRecord has_secure_password validates :email, presence: true, uniqueness: true validates :password_digest, presence: true has_many :friendships has_many :friends, through: :friendships has_many :invitations has_many :parties, through: :invitations end
# frozen_string_literal: true module ConsoleUtils::RequestUtils RequestParams = Struct.new(:params, :headers) class RequestParams AutoUid = -> (uid) do ConsoleUtils.request_auto_auth && ((uid.nil? || uid == true) ? ConsoleUtils.default_uid : uid) end attr_accessor :uid, :rest_options def i...
# frozen_string_literal: true RSpec.describe VideosFinder do let!(:video1) { create(:video, name: 'aaa_aaa.mp4', duration: 100) } let!(:video2) { create(:video, name: 'aaa_aaa.mp4', duration: 200) } let!(:video3) { create(:video, :deleted, name: 'bbb_abb.mp4', duration: 300) } let!(:video4) { create(:video, :d...
class CreateLoans < ActiveRecord::Migration def change create_table :loans do |t| t.string :loan_url t.string :title t.date :date_started t.integer :loan_duration_in_days t.integer :payment_cycle_in_days t.float :interest_in_percent t.float :loan_amount_in_btc t.flo...
#!/usr/bin/env ruby $LOAD_PATH.unshift File.expand_path "../../lib", __FILE__ require "newrelic_redshift_plugin" require 'optparse' options = OptionParser.new do |opts| opts.banner = <<-EOF Usage: newrelic_redshift_plugin ( run | install ) [options] EOF opts.on("-v", "--verbose", "Run verbosely") do NewReli...
class DashboardController < ApplicationController before_filter :authenticate_user! def show @hospitals = Hospital.all end end
class CriteriaController < ApplicationController layout 'admin' before_action :authenticate_user! before_action :load_user before_action :check_admin before_action :load_criterium, only: [:show, :edit, :update, :destroy] before_action :build_criterium, only: :create before_action :point_to_apt_object, onl...
class ToursController < ApplicationController before_action :authenticate_user! before_action :set_tour, only: [:show, :edit, :update, :destroy, :cancel_tour] # GET /tours # GET /tours.json def index @tours = Tour.all if params[:search] @search = TourSearch.new(params[:search]) @tours = @...
FactoryBot.define do factory :contract do name { Faker::Name.name } company vendor { association :vendor, company: company } category { association :category, company: company } end end
require 'curses' class Input attr_reader :history def initialize @history = [] end def gets @history.push(Curses.getch).last end end
module ActiveRecordRepo class TagMapper MAPS = { user: Models::User } class << self def map(tag) MAPS[tag] end end end end
Rails.application.routes.draw do devise_for :users, path: "", path_names: { sign_in: "login", sign_out: "logout", sign_up: "sign_up" }, controllers: { confirmations: "devise...
ActiveAdmin.register Classroom do menu priority: 4 show :title => :teacher do render "show" panel "Recent Checkins" do table_for Pin.order("updated_at desc").limit(10) do column :Student do |pin| link_to pin.user.name, [:admin, pin] end column "Checkin Date"...
#!/usr/local/bin/ruby -w # S3lib.rb module S3 module Authorized # Enter your public key (Amazon calls it an "Access Key ID") and # your private key (Amazon calls it a "Secret Access Key"). This is # so you can sign your S3 requests and Amazon will know who to # charge. class << self attr_...
module Sheets module Renderable def self.included(base) base.extend(ClassMethods) end module ClassMethods def renderable_formats Sheets::Utilities.subclasses_in(Sheets::Renderers).map(&:formats).flatten.uniq end end def method_missing(method_name, *args, &block) m...
# frozen_string_literal: true require 'find' require 'fileutils' require 'tmpdir' require 'json' import 'Base/Helpers/BaseHelper.rb' class AssetsCatalogHelper < BaseHelper def initialize(options = {}) super end def organize_resources_to_assets_catalog(options) add_resources_images_to_assets_catalog(op...
class LeadsController < ApplicationController before_filter :admin_user, only: [:new, :edit, :index, :update] def new @lead = Lead.new @lead_contact = LeadContact.new @text_field_setup = text_field_setup end def create # Took this out because #create_or_update_lead was being used many places d...
require 'test_helper' class ReadmeTest < ActiveSupport::TestCase test 'Basic readme creation & agent association' do readme = Readme.new( content: 'Hello' ) assert_not readme.save readme.agent = agents(:weather) assert readme.save assert_equal "Hello", agents(:weather).readme.content ...
require 'pg' class Chitter attr_reader :id, :name, :username, :text, :time def initialize(id, name, username, text, time) @id = id @name = name @username = username @text = text @time = time end def self.all if ENV['ENVIRONMENT'] = 'test' con = PG.connect :dbname => 'chitter_te...
class TagsController < ApplicationController def index @tags = ActsAsTaggableOn::Tag.most_used(20) end def show @protos = Proto.tagged_with(params[:id]) end end
require 'json' module Piebits class BuildSubmitter attr_reader :build BUILDS_ENDPOINT = '/api/builds' def initialize(api_token:, build:, faraday:) @api_token = api_token @build = build @faraday = faraday end def submit_build @faraday.post do |req| req.url BUILD...
class NotesController < ApplicationController before_action :set_note, only: [:show, :edit, :update, :destroy] def index @notes = Note.all render json: @notes end def show render json: @note end def new @note = Note.new render json: @no...
require_relative 'board' require_relative 'player' require_relative 'error' class Game attr_reader :board, :player1, :player2 attr_accessor :current_player def initialize(board, player1, player2) @board = board @player1 = player1 @player2 = player2 @current_player = red_player end def play ...
ActiveAdmin.register Technology do # f.input :author, :as => :select, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"] filter :name filter :description filter :type # Create sections on the index screen scope :all, :default => true scope :is_language scope :is_active form do |f| ...
class Photo < ActiveRecord::Base belongs_to :user has_many :albumphotos has_many :albums, through: :albumphotos mount_uploader :url, PhotoUploader end
class Game def initialize @board = Board.from_file(ARGV[0]) end def play until solved? render pos, value = get_input board[pos] = value end end def get_pos pos = nil until pos && board.valid_move?(pos) puts "Enter a position:" pos = gets.chomp.split(",").m...
class Oid < ActiveRecord::Base belongs_to :device validates :ping_request, :presence => true end
# frozen_string_literal: true require 'rails_helper' describe SessionsHelper, type: :helper do let(:user) { create :user } describe 'current_user' do it 'finds the current_user if a session exists' do session[:user_id] = user.id expect(current_user).to eq(user) end it 'returns nil if a s...
=begin Write a method that takes an Array as an argument, and reverses its elements in place; that is, mutate the Array passed in to this method. The return value should be the same Array object. You may not use Array#reverse or Array#reverse!. - input: array of elements - output: same array with elements indices reve...
# frozen_string_literal: true # App Main Controller # This class holds all the endpoints needed # to retrieve data. class App < Sinatra::Base helpers do # Checks if a date has valid format yyyy-mm-dd # # @param date [string] provided date. # @return [bool] true if is a valid date. def valid_d...
class ClientSerializer < ActiveModel::Serializer embed :ids attributes :id, :name, :phone, :email, :gravatar_image_url has_many :appointments def gravatar_image_url "http://www.gravatar.com/avatar/" + Digest::MD5.hexdigest(object.email.to_s.strip.downcase) end end
desc "" namespace :chain do desc "Chain state operations" namespace :state do desc "Export chain state" task :export, [:file, :node_directory] do |t, args| fh = File.open(args[:file], "w") if fh.nil? puts "unable to open the file #{args[:file]}!" exit(1) end state = ...
class Vip < ActiveRecord::Base acts_as_audited acts_as_authorizable named_scope :def_scope acts_as_reportable acts_as_commentable belongs_to :load_balancer, :class_name => "Node" has_many :vip_lb_pool_assignments has_many :lb_pools, :through => :vip_lb_pool_assignments belongs_to :ip_address, :de...
module GitHostingConf LOCK_WAIT_IF_UNDEF = 10 REPOSITORY_IF_UNDEF = 'repositories/' REDMINE_SUBDIR = '' REDMINE_HIERARCHICAL = true HTTP_SERVER = 'localhost' HTTP_SERVER_SUBDIR = '' TEMP_DATA_DIR = '/tmp/redmine_git...
# frozen_string_literal: true $LOAD_PATH << File.expand_path('..', __dir__) require 'lib/go_snowflake_client' require 'logger' class CommonSampleInterface attr_reader :db_pointer def initialize(database) @logger = Logger.new(STDERR) @db_pointer = GoSnowflakeClient.connect( ENV['SNOWFLAKE_TEST_ACCO...
require 'spec_helper' describe Customer do let(:customer){ FactoryGirl.create(:customer) } let(:customer_jones){ FactoryGirl.create(:customer, first_name: nil, last_name: "Jones") } describe "#full_name" do it "should join together the first and last names" do expect(customer.full_name).to eq("John Sm...
class Vehicle attr_reader :name, :manufacturer, :cost_in_credits, :passengers @@all = [] def initialize(vehicle_data) @name = vehicle_data["name"] @manufacturer =vehicle_data["manufacturer"] @cost_in_credits = vehicle_data["cost_in_credits"] @passengers = vehicle_data[...
class MessagesController < ApplicationController def hello @hello = 'Hello, View!' end end
class CreateBirthdayDealsTable < ActiveRecord::Migration def up create_table :birthday_deals do |t| t.integer :company_id t.integer :value t.string :hook t.string :restrictions t.string :how_to_redeem t.string :slug t.string :state t.datetime :created_at, null...
# frozen_string_literal: true module FacebookAds # An image will always produce the same hash. # https://developers.facebook.com/docs/marketing-api/reference/ad-image class AdImage < Base FIELDS = %w[id hash account_id name permalink_url original_width original_height].freeze class << self def fin...
require File.dirname(__FILE__) + '/../spec_helper' describe AlcaldesController do describe "handling GET /alcaldes" do before(:each) do @alcalde = mock_model(Alcalde) Alcalde.stub!(:find).and_return([@alcalde]) end def do_get get :index end it "should be successful" do ...
## General Comments - # 1. Use 'y' or 'n' to get boolean choices, instead of 1 from user eg - 'Do wish to continue' # 2. It is not clear from your prompts what is it for the input is needed. Please rectify this # 3. Use different terminory for product names eg 'A', using one 1 is creating confusion # 4. Display total ...
# frozen_string_literal: true RSpec.describe Api::V1::ResetPassword::CreateAction do let(:action) { described_class.new } describe '#call' do subject(:call) do action.call(input) end let(:input) do jsonapi_params( attributes: { email: email } ) end ...
class Types::ProjectType < Types::BaseObject description "A system project" field :id, ID, :null => false field :name, String, :null => false, :description => "Project's name" field :key, String, :null => false, :description => "Shortcut to identify a project by task name" field :tasks, [Types::TaskType], :nu...
json.array!(@audit_process_activities) do |audit_process_activity| json.extract! audit_process_activity, :id, :audit_id, :cprocess_id, :activity_id json.url audit_process_activity_url(audit_process_activity, format: :json) end
class HistoryController < ApplicationController require 'message' before_filter :require_user @@messagesPerPage = 25 def index @messages = Message.last(@@messagesPerPage).reverse render :index end end
class Cell def self.cell_by_type(poi_cell) case poi_cell.getCellType when cell.CELL_TYPE_NUMERIC NumericCell.new(poi_cell) when cell.CELL_TYPE_FORMULA FormulaCell.new(poi_cell) when cell.CELL_TYPE_BLANK BlankCell.new(poi_cell) end end def self.cell Java::OrgApachePoiSsUs...
# Write a method that returns a list of all substrings of a string that start # at the beginning of the original string. The return value should be arranged # in order from shortest to longest substring. def substrings_at_start(string) substring_arr = [] 0.upto(string.size - 1) do |index| substring_arr << stri...
require_relative "../../../lib/commands/vertical_segment" RSpec.describe Commands::VerticalSegment do describe '#new' do subject { Commands::VerticalSegment.new(state: state, args: args) } let(:state) { [['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O'], ['O', 'O', 'O']] } let(:x) { 3 } let(:y1) { 1 ...
module Brewery class AuthCore::User < ActiveRecord::Base has_and_belongs_to_many :roles has_and_belongs_to_many :assignable_roles, Proc.new { where hidden: false }, class_name: 'Brewery::AuthCore::Role' acts_as_authentic do |config| config.logged_in_timeout = 1.hours config.disable_perishable...
# Encoding: utf-8 class Search include PageObject link(:cta, :css => 'a.js-search-anchor') button(:taxonomy_cta, :css => '.taxonomy-cell .icn-search') link(:searchBtn, :css => '.search-button a') button(:cancel, :css => '.js-cancel') text_area(:input, :css => '.js-search-input') button(:clear,...
module Response def collection_serializer( data , serializer ) ActiveModel::Serializer::CollectionSerializer.new( data , serializer: serializer ) end end
class RecipesController < ApplicationController before_action :authenticate_admin!, only: [:update] before_action :authenticate_user!, except: [:index, :find_recipes, :intersecting_recipes] def index moods = params[:moods] flash.discard(:warning) @mood_names = Mood.all.map {|mood| mood.name } en...
class Api::BiometricInformationsController < ApiController filter_access_to :all def show @xml = Builder::XmlMarkup.new @biometric_information = BiometricInformation.find_by_biometric_id(params[:id]) respond_to do |format| if (params[:id].nil? or @biometric_information.nil?) render "si...
require 'spec_helper' module Naf describe HistoricalJobAffinityTabsController do let(:model_class) { HistoricalJobAffinityTab } it "should respond with index action nested under a job" do model_class.should_receive(:where).with({ historical_job_id: "1" }).and_return([]) get :index, historical_jo...
json.array!(@plantings) do |planting| json.extract! planting, :id json.url planting_url(planting, format: :json) end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
module ApplicationHelper def flash_class(level) case level.to_sym when :notice then "notification notice" when :success then "notification success" when :error then "notification error" else "notification error" end end end
# frozen_string_literal: true module TestProf # `before_all` helper configiration module BeforeAll class AdapterMissing < StandardError # :nodoc: MSG = "Please, provide an adapter for `before_all` " \ "through `TestProf::BeforeAll.adapter = MyAdapter`".freeze def initialize sup...
require 'rails_helper' RSpec.describe Bmi::Create do describe '#calculate' do context 'with a successfull response' do it 'returns Very severely underweight' do expect(Bmi::Create.new(1.77, 44).result).to eql([14.04, 'Very severely underweight']) end it 'returns Underweight' do ...
require 'spec_helper' feature "User interaction with his queue" do given(:user) { Fabricate(:user) } scenario "a user signs in" do visit login_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Sign in' expect(page).to have_content 'You have succes...
module MinceDynamoDb require 'singleton' require_relative 'config' require 'aws/dynamo_db' class Connection include Singleton def self.connection instance.connection end attr_accessor :connection def connection @connection ||= AWS::DynamoDB.new(access_key_id: Config.access_ke...
class DashboardsController < ApplicationController def index @item_listings = ItemListing.where(user: current_user) @stores = Store.where(user: current_user) end end
class AddIsReadedToUserRewards < ActiveRecord::Migration def self.up add_column :user_rewards, :is_readed, :boolean, :default=>false end def self.down remove_column :user_rewards, :is_reader end end
class Conference < ApplicationRecord validates :name, presence: true# Make sure the owner's name is present. validates :name, uniqueness: true has_many:committees has_many :tracks end
require 'spec_helper' describe 'gstreamer::tools' do describe command('gst-inspect-1.0 --version') do its(:exit_status) { should eq 0 } its(:stdout) { should match /GStreamer 1\.6\.1/ } end end
# coding: utf-8 class UsersController < CompanyController before_action :authenticate_user!, except: [:check_phone, :confirm_phone, :confirming_phone, :resend_confirmation_sms] before_action :skip_when_confirmed, only: [:confirming_phone, :confirm_phone] before_action :redirect_if_not_owner, only: [:destroy] d...
class AddDatabasetoTrait < ActiveRecord::Migration[5.1] def change add_reference :traits, :dataset, foreign_key: true end end
class Answers def initialize @choice = ["Disagree","Neutral","Agree","Strongly Agree"] end def get_choices @choice end end
require 'rails_helper' describe 'weather api' do it 'can register users' do post '/api/v1/users', params: { "email": "whatever@example.com", "password": "password", "password_confirmation": "password" } user_info = JSON.parse(response.body) expe...
module Elements class Compiler attr_reader :descriptor, :klass def initialize(descriptor) @descriptor = descriptor @compiled = false if @descriptor.parent.nil? @extends = Elements::Element else @extends = Elements::Types.const(@descriptor.parent.name) if @e...
class AppGenerator < VraptorScaffold::Base ORMS = %w( jpa hibernate ) argument :project_path class_option :package, :default => "app", :aliases => "-p", :desc => "Define base package" class_option :models_package, :aliases => "-m", :default => "models", :desc => "Define models ...
# frozen_string_literal: true require "post.rb" class PostsController < ApplicationController before_action :check_user_login, only: %i[new edit delete] def index if current_user @posts = Post.new().logged_in_user_feed_posts(current_user).page(params[:page]).includes(:user, :images) @post = Post.ne...
module Dom class Application < Domino selector "[data-application]" attribute :name, "[data-name]" attribute :status, "[data-status]" def closed? status[/closed/i] end def open? status[/open/i] end end end
require "fileutils" require "tinet/setting" require "tinet/shell" require "tinet/command/base" module Tinet module Command class Init < Base def run template = File.join(Tinet::ROOT, 'spec.template.yml') specfile = Tinet::DEFAULT_SPECFILE_PATH FileUtils.cp(template, specfile) ...
TAP_OWNER = "d12frosted" TAP_REPO = "emacs-plus" class UrlResolver def initialize(version, mode) name = "#{TAP_REPO}@#{version}" tap = Tap.new TAP_OWNER, TAP_REPO @version = version @formula_root = mode == "local" || !tap.installed? ? Dir.pwd : (tap.path.to_s.delete_suffix "/For...
class ChangeIngredientsRecipesTable < ActiveRecord::Migration def change drop_join_table :ingredients, :recipes create_table :ingredients_recipes do |t| t.integer :ingredient_id t.integer :recipe_id t.integer :quantity end end end
require 'rails_helper' RSpec.describe NewAnswerNoticeService do let!(:user) { create(:user) } let!(:question) { create(:question) } let!(:answer) { create(:answer, question: question, user: user) } it 'sends email to all question subscribers' do question.subscriptions.first.delete question.subscribers...
#!/usr/bin/env ruby require 'yaml' begin @@ec2conf = YAML::load(File.open(File.join(File.dirname(__FILE__), "ec2_credentials.yml"))) rescue Exception => e puts "Could not load config file: #{e.message}" exit! 1 end $LOAD_PATH << File.join(File.dirname(__FILE__), "..", "lib") @@ZONES = ['us-west-1', 'us-east-1...
module Admin class EquipmentController < Admin::ApplicationController include AdministrateExportable::Exporter # To customize the behavior of this controller, # you can overwrite any of the RESTful actions. For example: # # def index # super # @resources = Equipment. # page(par...
require 'recipiez/capistrano' set :application, "taygeta" set :rails_env, 'production' set :repository, "git@github.com:rebelcolony/taygeta.git" set :scm, :git set :branch, 'master' set :deploy_via, :remote_cache default_run_options[:pty] = true server "176.58.107.44", :web, :app, :db, primary: true set :num_serv...
require 'rails_helper' RSpec.describe FindCurrencyRatesByDateQuery do subject(:context) { described_class } describe '.call' do let!(:usd_1) { create(:currency_rate, :usd) } let!(:usd_2) { create(:currency_rate, :usd) } let!(:eur_1) { create(:currency_rate, :eur) } let!(:eur_2) { create(:currency_...
=begin #qTest Manager API Version 8.6 - 9.1 #qTest Manager API Version 8.6 - 9.1 OpenAPI spec version: 8.6 - 9.1 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require "uri" module SwaggerClient class ModuleApi attr_accessor :api_client def initialize(api_client ...
# frozen_string_literal: true module Vedeu module Cursors # Provides the mechanism to move a named cursor in a given # direction. # # @api private # class Move extend Forwardable def_delegators :cursor, :visible? # @param (see #initialize) # @...
require 'thor' require 'guard/version' module Guard # Facade for the Guard command line interface managed by [Thor](https://github.com/wycats/thor). # This is the main interface to Guard that is called by the Guard binary `bin/guard`. # Do not put any logic in here, create a class and delegate instead. # cl...
require 'rails_helper' RSpec.describe "scribbles/new", :type => :view do before(:each) do assign(:scribble, Scribble.new( :title => "MyString", :image => "MyString" )) end it "renders new scribble form" do render assert_select "form[action=?][method=?]", scribbles_path, "post" do ...
When(/^I wait until I see "([^"]*)" text$/) do |text| begin Timeout.timeout(DEFAULT_TIMEOUT) do loop do break if page.has_content?(text) sleep 3 end end rescue Timeout::Error raise "Couldn't find the #{text} in webpage" end end When(/^I wait until I see "([^"]*)" text, re...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :lockable, :confirmable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #==schema info #create_table "users", f...
class RemoveAddressFieldsFromBusinesses < ActiveRecord::Migration def change remove_column :businesses, :street_address remove_column :businesses, :additional remove_column :businesses, :city remove_column :businesses, :state remove_column :businesses, :zip_code end end
module Refinery module Caststone class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::Caststone engine_name :refinery_caststone paths = { shared: Pathname.new('refinery/admin'), fields: Pathname.new('refinery/caststone/admin/products/fields') ...
class ApplicationController < ActionController::Base before_action :authenticate_user! include Pundit after_action :verify_authorized, except: [:index, :new, :edit], unless: :skip_pundit? after_action :verify_policy_scoped, only: [:index], unless: :skip_pundit? rescue_from Pundit::NotAuthorizedError, with: ...
class BidsController < ApplicationController def create @bid = Bid.new(bid_params) @product = @bid.product @highest_bid = @product.bids.sort{|a| a.amount}.first.amount if (@bid.amount > @highest_bid)&&(@bid.amount > @bid.product.minprice)&&(@bid.user != @product.user) @bid.save redirect_t...