text
stringlengths
10
2.61M
# frozen_string_literal: true module Concerns module Loreable extend ActiveSupport::Concern cattr_accessor :lores do { 167 => 'Animals', 168 => 'Faith', 169 => 'Mortis Amaranthine', 170 => 'Lineages', 171 => 'Medical', 172 => 'Nature', 173 => 'Po...
class VotesController < ApplicationController before_action :set_votable def create vote = Vote.find_by(user: current_user, votable_id: @votable.id, votable_type: @votable.class.name) if vote vote.update_attributes(score: 1) else @votable.votes.create(user: ...
class ChangeOrderStatusInOrders < ActiveRecord::Migration def change remove_foreign_key :orders, column: :order_status_id end end
require "metrical/version" module Metrical def self.message "Please install metric_fu. It runs from the command-line now. And gem uninstall metrical metric_fu-metrical. Thanks :)" end end
require 'spec_helper' module LoginHelpers def log_in(user = nil) user ||= Factory(:user) visit admin_login_path fill_in 'email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' page.should have_content('Logged in!') end def log_out visit admin_path ...
class Genre < ActiveRecord::Base has_and_belongs_to_many :programs end
require 'rails_helper' RSpec.feature "Manufacturer", type: :feature do let!(:manufacturer) {Manufacturer.create!(name: "Stark Industries")} let!(:manufacturer) {Manufacturer.create!(name: "Bain Capital")} let!(:manufacturer) {Manufacturer.create!(name: "Wayne Enterprises")} before :each do user = create(:...
class AddNameAndDescriptionToUsers < ActiveRecord::Migration def change add_column :users, :name, :string, nil: false, default: "Default Name" add_column :users, :description, :text end end
class MpiDefect < ActiveRecord::Base belongs_to :mpi default_scope order(:created_at) default_scope order("created_at ASC") end
class StocksController < ApplicationController before_action :authenticate_user!, only: [:destroy] def index @stocks = Medicament.all end def show # @medicament = Medicament.search(params[:search]) end def new @stock = Stock.new({medicament_id: params[:medicament_id], drugstore_id: params[:dr...
class OxgarageParser def self.parse(filename) new(File.open(filename, 'rb')).to_hash end def initialize(file) @file = file end def to_hash { title: PaperExtractor.title(output), abstract: PaperExtractor.abstract(output), body: PaperExtractor.body(output) } end def output ret...
class FeedbackMailer < ActionMailer::Base include SendGrid sendgrid_category 'Feedback Mail' default :from => ENV['ADMIN_EMAIL'] default :fromname => "Mallow" default :to => ENV['ADMIN_EMAIL'] # send mail with feedback def feedback_mail(feedback) @feedback = feedback mail( :subject => "Feedback...
class UsersController < ApplicationController before_action :authenticate_user!, only: [:show, :edit, :update] before_action :ensure_admin!, only: :index before_action :set_user, only: [:show,:edit,:update] respond_to :html def index @trekker = User.trekker @trailblazer = User.trailblazer @admin ...
class HomeController < ApplicationController layout 'home' def index if signed_in? redirect_to startups_path end end end
class SupportsController < ApplicationController def contact_email @support = Support.new(params[:support]) if @support.valid? @support.send_contact_mail redirect_to root_path, :notice => "Support was successfully sent." else redirect_to :back, :notice => "You must fill all ...
module ChargeIO class ServerError < StandardError attr_accessor :code attr_accessor :entity_id def initialize(message, code=nil, entity_id=nil) super(message) @code = code @entity_id = entity_id end end end
#Add remote data source and pull in stories from Reddit, Mashable and Digg. # http://mashable.com/stories.json # http://digg.com/api/news/popular.json # These stories will also be upvoted based on our rules. No more user input! # Pull the json, parse it and then make a new story hash out of each story(Title, Categ...
When /^choose all the images to upload$/ do path = "./features/fixtures/images/image.jpg" [ :watch_background, :purchase_background, :splash_image, :tax_popup_logo, :tax_popup_icon, :player_background, :facebook_dialog_icon ].each do |attachment| attach_file(attachmen...
require_relative 'parser' require_relative 'race' class Main def initialize(file) @parser = Parser.new(File.read(file)) end def run @parser.run @race = Race.new(@parser.lines) @race.mount @race.print_stats end end m = Main.new("log/race.log") m.run
class DocumentsController < ApplicationController layout nil before_action :find_document, only: [:show, :destroy] before_action :authorize_document_access, only: [:show] before_action :validate_presence_of_upload, only: [:create] def index respond_to do |format| format.html { render } forma...
# frozen_string_literal: true require 'bolt/pal/yaml_plan' require 'bolt/pal/yaml_plan/evaluator' require 'psych' module Bolt class PAL class YamlPlan class Loader class PuppetVisitor < Psych::Visitors::NoAliasRuby def self.create_visitor class_loader = Psych::ClassLoader::Re...
class ResultController < ApplicationController before_action :show_now_working def index @result = Result.night.page(offset) end def show id = params[:id] @result = id ? Result.find(id) : Result.latest end def latest @result = Result.latest render :show end def create_comment ...
include Rails.application.routes.url_helpers class Documentations::ShowSerializer < ApplicationSerializer object_as :documentation identifier :slug attributes( :id, :slug, :title, :body, :created_at, :updated_at, ) type :string def documentable_name documentation.documentable...
module Refinery class Project < ActiveRecord::Base has_many :image_projects, :as => :project, :order => 'position ASC' has_many :images, :through => :image_projects, :order => 'position ASC' belongs_to :project_category, :class_name => "::Refinery::ProjectCategory" has_many :field...
# Source: https://launchschool.com/exercises/fd6b285b def multiply_all_pairs(arr_1, arr_2) results = [] arr_1.each do |val_1| arr_2.each do |val_2| results << val_1 * val_2 end end results.sort end multiply_all_pairs([2, 4], [4, 3, 1, 2]) == [2, 4, 4, 6, 8, 8, 12, 16]
class Command def execute raise 'You must implement this method in a descendant class.' end def un_execute raise 'You must implement this method in a descendant class.' end end
class ChangeMobilePhoneAndHomePhoneToString < ActiveRecord::Migration def up change_column :employees, :mobile_phone, :string change_column :employees, :home_phone, :string end def down remove_column :employees, :home_phone remove_column :employees, :mobile_phone add_column :employees, :home_...
# frozen_string_literal: true module Mutations class CreateItem < Mutations::BaseMutation null true argument :description, String, required: false, description: 'This is the item disciprion' argument :image_url, String, required: false, description: 'Image resource path' # rubocop:disable GraphQL/Ex...
task :you_need_to_install_any_dependencies do begin Bundler.setup(:default, :development) puts "You have all the dependencies you need!!\n\n" rescue Bundler::BundlerError => e with_guidance = "Oops! So near, yet so far. #{e.message} Run `bundle install` and all the dependencies you need will ...
class Category < ApplicationRecord has_many :series has_many :movies validates_presence_of :description end
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi # # A service client - single point of access to the REST API. # class MobileCenterClient < MsRest::ServiceClient ...
class FontMali < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/mali" desc "Mali" homepage "https://fonts.google.com/specimen/Mali" def install (share/"fonts").install "Mali-Bold.ttf" (share/"fonts").install "Mali-BoldItalic.ttf" ...
class ScenarioAlert # include Mongoid::Document # include Mongoid::Timestamps # # field :description # field :master_scenario_id # field :master_scenario_version, :type => Integer # field :read, :type => Boolean, :default => false # # embedded_in :scenario, :inverse_of => :scena...
require 'rails_helper' RSpec.describe PatientsController, type: :request do let!(:doctor) { create :doctor_with_specialization, :admin } let!(:patient) { create :patient } describe 'GET #edit' do it 'returns the edit template' do get edit_patient_path(patient.id) expect(response).to render_templ...
class Remove < ActiveRecord::Migration[6.0] def change remove_column :sensors, :sensor_group_id end end
class QuestionPresenter < BasePresenter delegate :id, :url, :title, :content, :user, :tags, :subscribers, to: :resource def fallback title end def normal_pretext "Hey, <%= user_url user %> just asked a question which you might be in the best position to answer" end def mention_pretext "Hey, <...
def print_grid!(center: [], clay:, water:, queue:, x_range: nil, y_range: nil, width: 100, height: 15) x, y = center x_range ||= (x - width / 2)..(x + width / 2) y_range ||= (y - height / 2)..(y + height / 2) y_offset = y_range.first < 0 ? -y_range.first : 0 y_range = (y_range.first + y_offset)..(y_range.last...
module Seek module JWS class Simulator UPLOAD_URL = "#{Seek::Config.jws_online_root}/webMathematica/model_upload_SEEK_xml.jsp" SIMULATE_BASE_URL = "#{Seek::Config.jws_online_root}/webMathematica/UItester.jsp" def simulate content_blob filepath=content_blob.filepath #this is n...
class Api::ApplicationController < ApplicationController private def require_http_auth_user authenticate_or_request_with_http_basic do |username, password| if @current_user = User.find_by_login(username) @current_user.valid_password?(password) else false end ...
require_relative 'token' require_relative 'token_classifier' module JackCompiler module Tokenizer class Processor attr_reader :tokens, :source def initialize(source) @source = source @tokens = [] end def tokenize! token = nil while code = source.pop ...
require 'sqlite3' module OpenAssets module Cache # The base class of SQLite3 cache implementation. class SQLiteBase attr_reader :db # Initializes the connection to the database, and creates the table if needed. # @param[String] path The path to the database file. Use ':memory:' for an in...
class FoodsController < ApplicationController before_action :authenticate_user! def index end def show end def new end def edit end def create food.update_attributes(permitted_params) if food.save redirect_to food, notice: "You've added a new food!" else render action: ...
class Rule < ActiveRecord::Base belongs_to :brand attr_accessible :name, :operator, :value end
require 'spec_helper' describe AdminObserver, :observer => true do # After Create #---------------------------------------------------------------------------- describe "after_create", :after_create => true do it "should email Administrator" do Admin.observers.enable :admin_observer do mailer =...
class AddIndex < ActiveRecord::Migration[6.1] def change add_index :users, [:email, :school_id], :unique => true end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ubuntu/trusty64" config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.provision "shell", path: "vagrant_setup/common.sh", preserve_order: true config.vm....
class FeedbacksController < ApplicationController def new @feedback = Feedback.new end def create @feedback = Feedback.new(feedback_params) if @feedback.save! flash[:success] = t(:feedback_create_success) else flash[:error] = t(:feedback_create_error) end redirect_...
class Web::Admin::SectionsController < Web::Admin::ProtectedApplicationController authorize_actions_for ::Section def index @sections = Section.only_sections.admin_order.page(params[:page]) end def show @section = Section.only_sections.find(params[:id]) end def new @section = SectionType.new ...
class AddColumnsToActivityMasters < ActiveRecord::Migration def change add_column :activity_masters, :href, :string add_column :activity_masters, :icon, :string end end
class CreateRoadmapDetails < ActiveRecord::Migration[6.0] def change create_table :roadmap_details do |t| t.references :roadmap_header, null: false, foreign_key: true t.text :sub_title t.text :pic_pass1 t.text :pic_pass2 t.text :pic_pass3 t.text :pic_pass4 t.integer :time...
module Fastlane module Actions class OneskyDownloadAllAction < Action def self.run(params) Actions.verify_gem!('onesky-ruby') require 'onesky' client = ::Onesky::Client.new(params[:public_key], params[:secret_key]) project = client.project(params[:project_id]) resp =...
class ReviewsController < ApplicationController before_action :set_order def new # authorize @review @review = Review.new @review.order = @order skip_authorization end def create # authorize @review @review = Review.new(review_params) @review.order = @order @review.save ski...
class User < ActiveRecord::Base include PgSearch validates :email, :password_digest, :session_token, :username, presence: true validates :username, uniqueness: true validates :password, length: { minimum: 6, allow_nil: true } validates :password, confirmation: true after_initialize :ensure_session_token ...
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |gem| gem.name = "g.raphael-radar-rails" gem.version = "0.3.0" gem.authors = ["Valentin Vasilyev"] gem.email = ["iamvalentin@gmail...
require_relative '../lib/advent' describe Advent do describe 'part_1' do it 'returns 3 for 1122' do expect(Advent.part_1('1122')).to eq 3 end it 'returns 4 for 1111' do expect(Advent.part_1('1111')).to eq 4 end it 'returns 0 for 1234' do expect(Advent.part_1('1234')).to eq 0 ...
authorization do role :guest do has_permission_on :trips, :to => [:show, :current] has_permission_on :users, :to => [:show, :edit, :update] do if_attribute :email => is { user.email } end end role :standard do includes :guest has_permission_on [:trips, :patients, :patient_cases, :implant...
require 'rails_helper' RSpec.describe Holiday do it 'exists' do attrs = { date: '2021-09-06', localName: 'Labor Day', name: 'Labour Day', countryCode: 'US', fixed: false, global: true, counties: nil, launchYear: nil, types: ['Public'] } holiday = Hol...
# -*- coding: utf-8 -*- require 'rubygems' require 'rmagick' require 'fileutils' require 'benchmark' require 'pp' require 'progressbar' # gem install progressbar def bmp2png(src) return "ERROR: フォルダが存在していません。#{src}" unless File.exists?(src) total = 0 # 対象ファイルをカウントする # TODO: リファクタリング Dir.glob(src + '/**/*....
# could be either visit '/static_pages/about' or visit about_path require 'spec_helper' describe "Static pages" do let(:base_title) { "ESL Support" } # Test case belongs to a home page # describe "Home page" do # visit is a capybara function, simulate visiting webpage provided #before {visit r...
# frozen_string_literal: true require 'bolt_spec/conn' require 'bolt_spec/files' require 'bolt_spec/integration' describe "when running a plan that creates targets", ssh: true do include BoltSpec::Conn include BoltSpec::Integration let(:modulepath) { File.join(__dir__, '../fixtures/modules') } let(:uri) { co...
class AddDataColumnToTrends < ActiveRecord::Migration def change add_column :trends, :date_time, :timestamp end end
remote_file "#{Chef::Config[:file_cache_path]}/go.go1.linux-amd64.tar.gz" do source "http://go.googlecode.com/files/go.go1.linux-amd64.tar.gz" mode "0644" end execute "unpack" do cwd "/usr/local" command "tar -zxf #{Chef::Config[:file_cache_path]}/go.go1.linux-amd64.tar.gz" creates "/usr/local/go" end pack...
require 'spec_helper' describe service('graylog2-web') do it { should be_enabled } it { should be_running} end describe file('/etc/graylog2/web/graylog2-web-interface.conf') do it { should be_file } its(:content) { should match /graylog2-server.uris/ } end describe file('/etc/sysconfig/graylog2-web'), :if =>...
class JobsController < ApplicationController def index @jobs = Job.all end def new @job = Job.new end def settings @job = Job.new end def create @job = Job.create(params.require(:job).permit(:name)) if @job.valid? redirect_to employees_path else flash[:errors] = @jo...
require 'rsruby' require 'statistic' class RStatistic include Statistic attr_reader :r_instance def initialize @r_instance = RSRuby.instance # is a singleton! @r_instance.library('nortest') @r_instance.library('class') @r_instance.library('e1071') # @r_instance.library('fBasics') # @r_...
class AddEntryLogoToEntry < ActiveRecord::Migration[5.0] def change add_column :entries, :entry_logo, :string end end
class Comment < ActiveRecord::Base belongs_to :post belongs_to :user validates :user, presence:true end
require 'digest' # represent member for account class MemberLancer include Mongoid::Document include Mongoid::Timestamps include Mongoid::Attributes::Dynamic include FullErrorMessages store_in database: 'sribulancer_development', collection: 'members' # include this module to provide calling link_to metho...
class ApplicationController < ActionController::API include Pundit include Extensions::Renderer rescue_from Pundit::NotAuthorizedError, with: :not_allowed def not_found render_error(I18n.t(:page_not_found), 404) end def not_allowed render_error(I18n.t(:forbidden), 403) end end
class PagesController < ApplicationController before_action :authenticate_user!, only: [ :new, :edit, :create, :update, :destroy ] before_action :set_project, only: [:show] before_action :set_project_from_current_user, only: [ :new, :edit, :move, :create, :update, :destroy ] before_action :set_pa...
require 'spec_helper' describe HomeController do describe "GET #index" do it "should assign a user with the given params" do get :index assigns[:user].should_not be_nil end describe "with integrated views" do render_views it "should respond successfully" do get :in...
require 'rails_helper' RSpec.describe Product, type: :model do describe 'Validations' do subject { described_class.new(name: "Chair", price: 180, quantity: 1, category: Category.new) } it "is valid with valid attributes" do expect(subject).to be_valid end #validates :name, presence: ...
require 'redmine' # Patches to the Redmine core. ActionDispatch::Callbacks.to_prepare do Dir[File.dirname(__FILE__) + '/lib/redmine_blocked_reason/patches/*_patch.rb'].each {|file| require_dependency file } Dir[File.dirname(__FILE__) + '/lib/redmine_blocked_reason/hooks/*_hook.rb'].each {|file| require_...
class PlantsController < ApplicationController def index respond_to do |format| format.html { @genus = Genu.order unless params[:genu_id].blank? @genus = @genus.where(:id => params[:genu_id]) end unless params[:search].blank? search_string = "%#{params...
module Common class FacilityUserRoleSerializer include FastJsonapi::ObjectSerializer attribute :facilities do |object| object.facilities.map do |facility| { id: facility[:id].to_s, name: facility[:name], code: facility[:code], } end end attrib...
class NotificationsController < ApplicationController before_filter :login_required filter_access_to :all def index mark_read unless params[:filter].blank? @filter = params[:filter] @notifications = Notification.apply_filter(params[:filter]).paginate(:page => params[:page], :per_page => 10)...
class Comment < ActiveRecord::Base belongs_to :article # the line belongs_to :article, which sets up an Active Record association. many to one relationship #These two declarations (belongs_to and has_many, in comment.rb and article.rb) enable a good bit of automatic behavior. For example, if you have an instance ...
# typed: true class CreateWhitelabelSystemExtensions < ActiveRecord::Migration[6.0] def change create_table :whitelabel_system_extensions do |t| t.text :rfc t.references :comment, null: false, foreign_key: true t.timestamps end end end
require "./board.rb" class CLI def run @should_exit = false until @should_exit handle_input gets end end private STRING_REPRESENTATION = { closed: ' #', flagged: ' !', question_marked: ' ?', red_mine: ' X', mine: ...
class UserSerializer < ActiveModel::Serializer attributes :uuid, :name, :email end
#!/usr/bin/env ruby # This file is under the BSD 3 Clause (BSD-3-Clause) License # vim: set ts=2 sw=2 sts=2 noet: # # ---BEGIN COPYRIGHT NOTICE--- # Copyright 2018 Christopher L. Ramsey # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following co...
class Pass < ActiveRecord::Base validates_presence_of :email validates_presence_of :billing_ref validates_presence_of :valid_until def self.create_month!(email:, billing_ref:) create!( email: email, billing_ref: billing_ref, valid_until: 1.month.from_now ) end end
class Maid < ActiveRecord::Base validates :name, presence: true validates :number, presence: true, uniqueness: true has_one :twitter_account has_one :blog def tweets self.twitter_account.tweets.order('published_at DESC') end def pictures pictures = [] tweets = self.twitter_account.tweets.or...
class Item < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to_active_hash :area belongs_to_active_hash :category belongs_to_active_hash :charge belongs_to_active_hash :condition belongs_to_active_hash :day has_one :buy belongs_to :user has_one_attached :image ...
module Compartment module Core module Storage def has_production_attached_file(name, path, settings={}) if Rails.env.production? && Compartment.production_file_storage == :s3 settings.merge!({ :storage => :s3, :s3_credentials => { :access_key_id => ENV...
module Beats # Domain object which models a kit sound playing a rhythm. For example, # a bass drum playing every quarter note for two measures. # # This object is like sheet music; the AudioEngine is responsible creating actual # audio data for a Track (with the help of a Kit). class Track class Invalid...
# Text menu class for controlling railroad class Menus MAIN_MENU = { '1' => { label: 'Создать: станцию, поезд, маршрут', func: :creating_menu }, '2' => { label: 'Редактировать: поезд, маршрут', func: :editing_menu }, '3' => { label: 'Информация и движение поезда', func: :moving_menu }, '0' => ...
shared_examples_for 'Coordinate#degrees' do subject { instance.degrees } context 'when int' do let(:degrees) { 48 } it { expect(subject).to eql(48) } it { expect(subject).to be_an(Integer) } end context 'when float' do let(:degrees) { 48.0 } it { expect(subject).to eql(48) } it { exp...
class Item < ActiveRecord::Base attr_accessible :name, :rating belongs_to :poll has_many :item_image_urls, :dependent => :destroy def self.create_etsy_item(etsy_item, poll_id) item = Item.new item.poll_id = poll_id item.name = etsy_item.result["title"] item.rating = 0 item.times_rated = 0 ...
class String # Translate a four-character code to some numeric value apparently used # internally in some way by OS X. def to_fcc raise "#{self} is #{self.length} characters - only four-character strings can be four-character encoded... duh" unless self.length == 4 self.unpack('N').first end end
class CartDetailsPage < Page def initialize @cart = Main::Carts.new @pipe = Pipe.new end def load(id) super() do @cart.load_from_db id: id, attribute_group: :details, limit: 1 end end def html super do @pipe.get(:html, data_by_type: { @cart.data_obj_name => @cart.load...
require 'rails_helper' RSpec.describe "genres/new", type: :view do before(:each) do assign(:genre, Genre.new( :name => "MyString", :parent_id => 1, :is_deleted => false )) end it "renders new genre form" do render assert_select "form[action=?][method=?]", genres_path, "post" d...
# frozen_string_literal: true class Statement def print_statement(transactions) @transactions = transactions print_header print_transactions end private def print_header print "date || credit || debit || balance\n" end def print_transactions @transactions.reverse.each do |t| pr...
module ActiveRecord module Acts module Optionable module SpecifyOption module ClassMethods # Setup a default value at the class level. def specify_option(option_name, opts = {}) name = option_name.to_s optionable_specified_options[name] = Option.new_readon...
# crypto_helper.rb # # Description:: Helpers modules # Author:: Ollivier Robert <roberto@keltia.freenix.fr> # Copyright:: © 2001-2009 by Ollivier Robert # # $Id: crypto_helper.rb,v 1d557f2f8b62 2013/03/05 14:28:17 roberto $ # == String # # Small addon to String class # class String # === condensed # # Conden...
# merges "flat/simple" hashes. Values of the same key # are added together in the resultant hash. def combine_hashes(*hashes) final_hash = {} hashes.each do |this_hash| # where matching, add the values. final_hash = final_hash.merge(this_hash) { |_key, oldval, newval| newval + oldval } end re...
class DiagnosisController < SecuredController def initialize super @diagnosis_service = DiagnosisService.new end def create diagnosis = @diagnosis_service.create(diagnosis_params) render json: diagnosis end def get diagnosis = @diagnosis_service.get(params[:id]) render json: diagnosi...
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module MobileCenterApi module Models # # Model object. # # class AppInvitationDetailResponse # @return [String] The uniqu...
require 'json' require 'rest-client' class Sendgrid attr_accessor :api_user attr_accessor :api_key attr_reader :uri def initialize(api_user, api_key) @api_user = api_user @api_key = api_key @base_uri = 'https://api.sendgrid.com/api/' @date = '1' # this instructs sendgrid to retrieve the failur...
class AddCommentToUsers < ActiveRecord::Migration[5.1] def change add_column :sports, :comment, :string end end