text
stringlengths
10
2.61M
after_bundler do get_vendor_javascript 'https://raw.github.com/kswedberg/jquery-expander/master/jquery.expander.js', 'jquery.expander' require_javascript 'jquery.expander' # up to you to hook it up in document.ready end __END__ name: Jquery expander description: Add jquery expander script to compress/expand blo...
# config-utils.rb # # In the class that you're configuring: # # class MyClass # def init(*args, &block) # config = ConfigStruct.block_to_hash(block) # # process your config ... # end # end # # To configure MyClass: # # MyClass.new.init do |c| # c.some = "config" ...
# frozen_string_literal: true require_relative 'mixins/command' # split-window (alias: splitw) # [-bdfhIvPZ] # [-c start-directory] [-e environment] [-l size] [-t target-pane] [-F format] # [shell-command] # -e takes the form ‘VARIABLE=value’ and sets an environment # variable for the newly created window; ...
class RolesController < ApplicationController before_action :set_locale def show @role = Role.find!(request.path) setup_content_item_and_navigation_helpers(@role) render :show, locals: { role: @role } end private def set_locale I18n.locale = params[:locale] || I18n.default_locale end end
namespace :db do desc "populates the database" task :populate, [:amount] => :environment do |t, args| amount = args[:amount].to_i Rake::Task["db:populate_users"].invoke(amount) Rake::Task["db:populate_exercises"].invoke(amount) Rake::Task["db:populate_trainings_sessions"].invoke(amount) Rake::Task["db:popu...
# -*- mode: ruby -*- # vi: set ft=ruby : # Sergey's Vagrant test cluster # Copy it into a separate directory as Vagrantfile to avoid collisions servers=[] (1..3).each do |srv| servers << { :num => srv, :hostname => "devops#{srv}", :ip => "192.168.100.10#{srv}", :box => "travisrowla...
class Destination < ApplicationRecord validates_presence_of :city, :state, :latitude, :longitude, :population has_many :routes, dependent: :destroy has_many :trips, through: :routes def self.search(term) dest = Destination.arel_table where(dest[:city].matches("%#{term}%").or(dest[:state].matches("%#{t...
class AddPetsToApplicationPets < ActiveRecord::Migration[5.2] def change add_reference :application_pets, :pet, foreign_key: true end end
class ArticlesController < ApplicationController before_filter :authenticate_user! def academy_board if Tag.any? @academy_board = true @tags_one = Tag.order('id asc').limit(3) @tags_two = Tag.order('id asc').offset(3).limit(2) else redirect_to root_path end end def index ...
# 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
module Haenawa module Commands class SendKeys < Command VALID_KEYS = [ '${KEY_ENTER}' ] def validate if target.blank? @step.errors.add(:target, :missing) elsif !VALID_STRATEGIES.include?(strategy) || locator.blank? @step.errors.add(:target, :inv...
require 'test_helper' class Finerworks2Test < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Finerworks2::VERSION end end
FactoryBot.define do factory :address do zipcode { "03004-001" } public_place { "Rua do Gasometro" } number { "100" } complement { "Complemento" } neighborhood { "Brás" } city { "São Paulo" } state { "SP" } ibge_code { "12345" } end end
class Vehicles attr_reader :make, :model, :wheels def initialize(make, model, wheels) @make = make @model = model @wheels = wheels end def to_s "#{make} #{model}" end end class Car < Vehicles def initialize(make, model) super(make, model, 4) end end class Motorcycle < Vehicles ...
class Restaurante def qualifica(nota, msg="Obrigado") puts "A nota do restaurante foi #{nota}. #{msg}" end end
class Telefone < ApplicationRecord belongs_to :pessoa validates :ddd, :numero, :tipo, presence: true validates_with TelefoneValidator def tem_preferencial? return (Telefone.where(pessoa_id: self.pessoa_id, preferencial: true).blank?) ? false : true end end
require "rails_helper" RSpec.shared_context "with finished deployment" do before { create(:deployment, :finished, project: project) } end RSpec.shared_examples "with failed deployment" do before { create(:deployment, :failed, project: project) } end RSpec.shared_examples "successful publish" do it { is_expecte...
module ::Forem class Engine < Rails::Engine isolate_namespace Forem class << self attr_accessor :root def root @root ||= Pathname.new(File.expand_path('../../', __FILE__)) end end initializer 'engine.helper' do |app| ActionView::Base.send :include, Forem::Applicat...
class Editar < SitePrism::Page element :search_btn, '#searchbutton' element :search_field, '#query_string' element :task, '#pagecontent > table > tbody:nth-child(3) > tr > td:nth-child(2) > a' def SearchTask search_btn.click search_field.set(task) task.click end end
class ShowOffUtils def self.create dirname = ARGV[1] return help('create') if !dirname Dir.mkdir(dirname) if !File.exists?(dirname) Dir.chdir(dirname) do # create section Dir.mkdir('one') # create markdown file File.open('one/slide.md', 'w+') do |f| f.puts "!SLIDE" ...
atom_feed do |feed| feed.title @title latest = @videos.sort_by(&:created_at).last feed.updated(latest && latest.created_at) @videos.each do |video| feed.entry(video) do |entry| entry.url video_path(video) entry.title "Video saved " + video.created_at.strftime("%A, %B %Y") entry.summ...
class Review < ActiveRecord::Base belongs_to :user belongs_to :concert #custom_writer def concert_attributes=(concert_attributes) self.create_concert(concert_attributes) if concert_id.nil? end end
module FormObject class DateTimeType class << self def process(params, name) value = params[name] || params[name.to_s] return value if value && value.class == DateTime return value.to_datetime if value && value.respond_to?(:to_datetime) year = params["#{name}(1i)"] ...
# frozen_string_literal: true class StudentComponents::StudentTable < ViewComponent::Base delegate :excluding_deleted?, :show_deleted_url, :student_group_name, :policy, to: :helpers def initialize students = StudentTableRow.includes(:tags, { group: { chapter: :organization } }) @pagy, @students = yield(st...
class AddMiniDraftToRounds < ActiveRecord::Migration[5.0] def change reversible do |dir| dir.up do add_column :rounds, :mini_draft, :boolean Round.where('deadline_time > ?', Round::SUMMER_MINI_DRAFT_DEADLINE).first.update(mini_draft: true) Round.where('deadline_time > ?', Round::WINT...
# == Schema Information # # Table name: users # # id :bigint not null, primary key # first_name :string not null # last_name :string not null # email :string not null # breed :string # about_me :text # password_digest :str...
class CreateTravelPlans < ActiveRecord::Migration[5.0] def change create_table :travel_plans do |t| t.references :user, index: true, foreign_key: { on_delete: :cascade }, null: false t.integer :type, index: true, null: false, default: 0 t.daterange :departure_date_rang...
describe EasyRakeTaskRepeatingEntities do it 'create issue to be repeated with righ params' do author = FactoryGirl.create(:user, :lastname => 'Author') assigned_to = FactoryGirl.create(:user, :lastname => 'Assignee') issue = FactoryGirl.create(:issue, :reccuring, :author => author, :assigned_to => assi...
=begin rdoc Пользователи =end class User < ActiveRecord::Base attr_accessible :login, :email, :password, :password_confirmation, :city_name, :active, :role_ids acts_as_authentic do |c| c.login_field = 'email' end # Associations has_and_belongs_to_many :roles has_many :magazines has_many :products ...
# -*- coding: utf-8 -*- module TextToNoise class NoiseMapping include Logging attr_accessor :targets, :matcher_conditions, :filter_conditions def initialize( expression_or_map, &block ) debug "Parsing expression: #{expression_or_map.inspect}" @matcher_conditions = [] @filter_condit...
json.metadata do json.users_count @users_count json.books_count @books_count json.requests_count @requests_count json.conversations_count @conversations_count end
class Api::GamesController < Api::ApplicationController before_action :authenticate_user! def show game = Game.find(current_user.game&.id) render_json game, include: {seats: {user: true, river: :tiles, hand: :tiles}} end def create room = current_user.room head :unprocessable_entity unless r...
module Refinery module Fg class Teacher < Refinery::Core::BaseModel attr_accessible :name, :desc, :content, :works, :avatar_id, :title, :position acts_as_indexed :fields => [:name, :title, :works, :desc, :content] validates :name, :presence => true, :uniqueness => true belongs_to :avat...
class Auction::ImportWorker include Sidekiq::Worker def initialize @wow_client = WowClient.new(logger) end def perform(auction_hash) logger.info "Performing import job auction_hash = #{auction_hash.inspect}" auction_hash.deep_symbolize_keys! item = @wow_client.create_or_update_item(auction_...
class Incident < ApplicationRecord has_many :posts has_many :users has_many_attached :images acts_as_taggable # Alias for acts_as_taggable_on :tags end
module Spree module Core # THIS FILE SHOULD BE OVER-RIDDEN IN YOUR SITE EXTENSION! # the exact code probably won't be useful, though you're welcome to modify and reuse # the current contents are mainly for testing and documentation # To override this file... # 1) Make a copy of it in your ...
json.array!(@cabins) do |cabin| json.extract! cabin, :id, :name, :available, :gender, :description, :max, :people_count json.url cabin_url(cabin, format: :json) end
require 'spec_helper' describe Codex::Loader do before do @path = 'minitest/etc/sample_journal.codex' @subject = Codex::Loader.new(@path) end def subject @subject end describe '#entries' do before do @entries = subject.entries end it 'has the right number of entries' do ...
class WorkersController < ApplicationController load_and_authorize_resource param_method: :workers_params before_action :form_variables, only: [:new, :edit, :create, :update] def index if params[:workshop_id] @workers = Worker.accessible_by(current_ability).where(workshop_id: params[:workshop_id]...
unless Rails.env.production? namespace :coveralls do desc 'Push latest coverage results to Coveralls.io' task push: :environment do require 'coveralls' Coveralls.push! end end end
class LiveLeagueMatch < ActiveRecord::Base validates_presence_of :players, :radiant_team, :dire_team, :lobby_id, :match_id, :league_id, :scoreboard validates_uniqueness_of :match_id end
class AddImageToPhoneBookEntry < ActiveRecord::Migration def change add_column :phone_book_entries, :image, :string end end
require 'spider/rules' module Spider class Agent attr_reader :schemes def schemes=(new_schemes) @schemes = new_schemes.map(&:to_s) end def visit_hosts @host_rules.accept end def visit_hosts_like(pattern=nil,&block) if pattern visit_hosts << pattern elsif bl...
class AddDurationToEvents < ActiveRecord::Migration def change add_column :events, :duration, :interval end end
require 'rails_helper' describe Page do subject { create(:page, :reindex, content: '1234567890') } it 'can be searched' do subject expect(Page.search('1234567890').total_count).to eq(1) end it 'enqueues PageRelayJob on update only' do expect { subject }.to_not have_enqueued_job(PageRel...
class Admin::AttachmentsController < Admin::BaseController def index @attachments = Attachment.paginate :page => params[:page], :per_page => @per_page, :order => "id DESC" end def show @attachment = Attachment.find(params[:id]) end def new @attachment = Attachment.new e...
# 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...
# Rubyには型が存在する # 例えば文字列型(String),整数型(Integer) puts "実行1" puts 5 puts "5" # 実行すると両方とも5と表示される # 同じ表示でも、「""」で囲うものと囲わないものでは意味が違ってくる puts "---------------------" puts "実行2" puts 5 + 3 puts "5 + 3" puts "5" + "3" # 実際の実行結果は # 8 # 5 + 3 # 53 # になる # ("")で囲ったものは、文字列型として扱われ、囲っていないものは、整数型として扱われる # 1行目は、整数型の計算である「5+3」が行われ、...
# frozen_string_literal: true require 'contracts/application_contract' require 'entities/coin' module Contracts module Coins class CreateCoinContract < ApplicationContract schema do required(:denomination) .filled(:string) .value(included_in?: Entities::Coin::DENOMINATIONS.keys...
class RegistrationsController < Devise::RegistrationsController before_action :one_user_registered?, only: [:new, :create] def new super end def create super end def update super end protected def one_user_registered? if User.count == 1 if user_signed_in? redirect_to...
class ChargesController < ApplicationController def new end def create # Amount in cents @amount = 500 Stripe.api_key = Rails.application.secrets.secret_key token = params[:stripeToken] # Create the charge on Stripe's servers - this will charge the user's card once begin charge...
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundat...
require 'spec_helper' describe GroupDocs::Questionnaire::Collector do it_behaves_like GroupDocs::Api::Entity include_examples GroupDocs::Api::Helpers::Status subject do questionnaire = GroupDocs::Questionnaire.new described_class.new(:questionnaire => questionnaire) end describe '.get!' do bef...
class Bookmark < ActiveRecord::Base belongs_to :user has_many :likes default_scope { order('created_at DESC') } end
require 'spec_helper' describe KitsController do describe "#index" do it "should display all the published kits and some featured programs" do kit = create(:kit, published: true) program = create(:program, featured: true) unpublished = create(:kit, published: false) get :index assig...
RSpec.describe BidType do it { is_expected.to have_attribute :name } it { is_expected.to validate_uniqueness_of :name } it { is_expected.to validate_presence_of :name } end
# To finish the installation, you'll need to add it to your layout. I don't do that # here for fear of conflicts. # <!--[if lt IE 9]> # <script src="<%= javascript_include_tag "html5" %>"></script> # <![endif]--> after_bundler do # Get html5 shiv for IE, but don't require it - it will be included # inside a condit...
post '/signup' do user = User.new(params[:user]) if user.save # what should happen if the user is saved? redirect "/home" else # what should happen if the user keyed in invalid date? # redirect '/' @email_message = user.errors.full_messages.join(',') erb :"/static/index" end end post '/...
class API::V1::RootController < API::BaseController def index hash = {} if current_user hash.merge!({ :account => { :href => api_v1_user_url(current_user) } }) end respond_with hash.to_json end end
module Darky module Utils class << self def default_options { :adapter => :open4, :dir => File.expand_path(% . ) } end end module ClassMethods def attr_private_reader *args args.each { |o| attr_reader o or private o } end def dele...
class CreateHourlyForecasts < ActiveRecord::Migration def change create_table :hourly_forecasts do |t| t.integer :time t.text :summary t.text :icon t.float :precip_probability t.float :temperature t.float :humidity t.float :wind_speed t.float :visibility t.re...
class Pitch < ActiveRecord::Base belongs_to :user has_many :comments has_many :external_links, as: :linkable has_many :votes, as: :votable validates :title, length: { maximum: 50 } validates :tagline, length: { maximum: 140 } validates :description, length: { maximum: 3000 } GRAVITY = 1.1 attr_acce...
require 'i18n' require 'cinch' require 'openra/irc_bot/dictionary' require 'openra/irc_bot/plugins' module Openra class IRCBot < Cinch::Bot def self.load! return false if defined?(@loaded) Dictionary.add_path( File.join(__dir__, '../../', 'config', 'dictionaries') ) @loaded = tr...
require 'test_helper' class UpdatingShowsTest < ActionDispatch::IntegrationTest setup do @show = shows(:show1) @updated_name = 'Updated Show Display' end test 'valid -> status' do update_valid assert_equal 200, response.status end test 'valid -> type' do update_valid assert_equal Mi...
require 'formula' class GenymotionPeco < Formula homepage 'https://github.com/satoshun/genymotion-peco' url 'https://raw.githubusercontent.com/satoshun/genymotion-peco/4270def977473a48ed9feed97b035786a9585627/genymotion_peco' sha256 '2862ff209e0daaeeacfdbb211fa1f7686f2c5e094d2dcc638b6fa92ded2f0100' def instal...
class MarketCoin < ActiveRecord::Base # informations validates :symbol, presence: true validates :name, presence: true validates :coin_name, presence: true validates :code, presence: true, uniqueness: true validates :full_name, presence: true # image validates :logo_url, presence: false # details ...
namespace :check do namespace :migrate do desc "Forces re-index of ProjectMedias associated with a set of team_ids and optionally a start position for ProjectMedia IDs. Example: bundle exec rake check:migrate:reindex_alegre_text_project_medias['team-slug',last-project-media-id,model-name]" task :reindex_alegr...
# frozen_string_literal: true require 'rails_helper' RSpec.describe LandlordsController, type: :controller do let(:current_user) { create(:user) } let(:session) { { user_id: current_user.id } } let(:params) { {} } describe 'PUT #update' do subject { put :update, params: params, session: session } le...
# frozen_string_literal: true require 'rails_helper' RSpec.describe Users::List, type: :action do describe 'Inputs' do subject { described_class.inputs } it { is_expected.to be_empty } end describe 'Outputs' do subject { described_class.outputs } it { is_expected.to include(list: { type: Enum...
# frozen_string_literal: true class Artist < ActiveRecord::Base has_many :songs has_many :genres, through: :songs # extend Slugifiable::ClassMethods # include Slugifiable::InstanceMethods def slug name.downcase.split(" ").join("-") end def self.find_by_slug(slug) all.find { |artist| artist.slu...
class Member < User has_many :workspace_users, foreign_key: :user_id has_many :workspaces, through: :workspace_users end
FactoryBot.define do factory :monthly_point do association :user, factory: :user points { 0 } start_date { Date.today.beginning_of_month } end_date { Date.today.end_of_month.end_of_day } end end
class CreateInstallments < ActiveRecord::Migration[5.2] def change create_table :installments do |t| t.integer :present_value t.decimal :number_of_installments t.decimal :monthly_interest_rate t.timestamps end end end
class PoorPokemon::Move attr_accessor :name, :dmg, :type, :pp def initialize (name, dmg, type, pp) @name = "#{name} (#{type})" @dmg = dmg @type = type @pp = pp end def usable? #returns true if move has enough PP to be used @pp>0 end end
# frozen_string_literal: true module Api # # jiman-api controller of the jimen # class JimenController < ApiController before_action :authenticated?, only: %i[create update] before_action :check_id, only: %i[show jump update] before_action :parse_json, only: %i[create update] def index @...
require 'vagrant' module Migrant module Provisioners class ChefSolo < Base include Util register :chef_solo def initialize(env) super end def prepare end def upload server = @environment.server vagrant_environment = Vagrant::Environment.new ...
class TeacherRelationship < ApplicationRecord belongs_to :teacher belongs_to :student end
require 'deviantart/base' module DeviantArt ## # Access token class for authorization code grant class AuthorizationCode::AccessToken < Base attr_accessor :expires_in, :status, :access_token, :token_type, :refresh_token, :scope end end
class UsersController < ApplicationController before_action :security, only: [:show, :favorites, :save_favorite, :destroy_favorite] def show @user = User.find(params[:id]) end def new @user = User.new() end def create @user = User.new(user_params) if @user....
class Identity < ActiveRecord::Base belongs_to :user, class_name: Spree::User, inverse_of: :identities validates :provider, inclusion: { in: %w(twitter facebook gplus) } end
require 'thor' require 'open-uri' require 'dashing/version' module Dashing class CLI < Thor include Thor::Actions attr_reader :name class << self attr_accessor :auth_token def hyphenate(str) return str.downcase if str =~ /^[A-Z-]+$/ str.gsub('_', '-').gsub(/\B[A-Z]/, '-\&')...
class AddPositionToHiringCompany < ActiveRecord::Migration def change add_column :hiring_companies, :position, :integer end end
# Item Class class Item attr_reader :description attr_reader :price attr_reader :total_tax attr_reader :total_price attr_reader :tax_round def initialize(description, price, imported = false, tax_exempt = false) @description = description @price = price @imported = imported @tax_exempt = ...
module Service class MessageList < BaseService step :query step :order def query Message.all.page(params.fetch('page', 1)).per(20) end def order result.order(created_at: :desc) end end end
module TinyMCE VERSION = "3.4.7" TINYMCE_VERSION = "3.4.7" end
class SessionsController < ApplicationController before_action :find_user, only: [:show, :index] skip_before_action :current_user def index # @user = User.find_by(id: params[:id]) if current_user && session[:user_id] @products_sold =[] orders_paid= Order.where(status: "paid") orders_pai...
class Mahjong::Field::RiverSerializer < ApplicationSerializer has_many :tiles end
class AddIpAddressToAnonymousToken < ActiveRecord::Migration def self.up add_column :anonymous_tokens, :ip_address, :string add_index :anonymous_tokens, :ip_address end def self.down remove_index :anonymous_tokens, :ip_address remove_column :anonymous_tokens, :ip_address end end
class AllController < ApplicationController before_action :authenticate_user! def index @movies = current_user.movies.page(params[:page]).per(15) @shows = current_user.shows.page(params[:page]).per(15) end end
#!/usr/bin/env ruby def promtAndGet(prompt) print prompt str = gets.chomp throw :quitRequested if str == "!" return str end catch :quitRequested do name = promtAndGet("name:") age = promtAndGet("age:") sex = promtAndGet("sex:") puts name,age,sex end
class CreateCoins < ActiveRecord::Migration[6.1] def change create_table :coins do |t| t.string :coin_api_id t.string :name t.string :symbol t.string :image t.decimal :current_price t.decimal :price_change_percentage_1h_in_currency t.decimal :high_24h t.decimal :low...
module RedmineCharts module RangeUtils include Redmine::I18n @@types = [ :months, :weeks, :days ] @@days_per_year = 366 @@weeks_per_year = 53 @@months_per_year = 12 @@seconds_per_day = 86400 def self.types @@types end def self.options @@types.collect do |type| ...
class AddAuditReports < ActiveRecord::Migration def up create_table :audit_reports do |t| t.references :user, type: :uuid t.integer :wegoaudit_id t.string :name t.json :data t.timestamps end add_foreign_key :audit_reports, :users end def down drop_table :audit_repor...
class UserEvent < ApplicationRecord belongs_to :attended_event, class_name: 'Event' belongs_to :event_attender, class_name: 'User' end
# Require core library require "middleman-core" # Extension namespace module Middleman module Swiftype class << self attr_accessor :swiftype_options end class Options < Struct.new(:api_key, :engine_slug, :pages_selector, :process_html, :generate_sections, :generate_info, :generate_image, :title_s...
class AccountsController < ApplicationController STEPS = [:adapter, :keychain, :key, :remote] private def init_wizard puts "starting new wizard" session[:new_account] = {} end def store(step, data) session[:new_account][step.to_sym] = data pp session[:new_account] end def fetch(step) ...
class TowersofHanoi attr_accessor :towers def initialize(towers = nil) towers.nil? ? populate_board(3) : @towers = towers # @disks = disks end def populate_board(disks) @towers = Array.new(3) { [] } (1..disks).each do |i| @towers[0].unshift(i) end end def move(string=nil) i...
require 'test_helper' class LikeCourseControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:example) log_in_as(@user) @course = courses(:one) @like = like_courses(:one) end test "like should be valid" do assert_not @like.valid? end end
require 'json' require 'uri' require 'net/http' require 'openssl' module ThreeScale module API class HttpClient attr_reader :endpoint, :admin_domain, :provider_key, :headers, :format, :keep_alive def initialize(endpoint:, provider_key:, format: :json, verify_ssl: true, keep_alive: false) @en...
module ApplicationHelper def conditional_link_to(title, url, action, model) link_to title, url if can? action, model end def conditional_link_to_remote(title, url, action, model) link_to title, url, :remote => true if can? action, model end def conditional_link_to_delete(title, url, action, m...