text
stringlengths
10
2.61M
class Mail::ManagedRecordsController < Mail::ApplicationController before_action :fetch_managed_record def created @subject = I18n.translate(@record.model_name.i18n_key, scope: 'mail.managed_record.created.subject', record: @record.label) end private def fetch_managed_record if params[:managed...
class Syobocalite::Program # Slackに投稿するための文言に整形する # @return [String] def format start_time = st_time.strftime("%H:%M") elements = [] elements << "#{start_time}〜【#{ch_name}】#{title}" if story_number >= 1 || !sub_title.blank? str = "" str << "第#{story_number}話" if story_number >= 1 ...
# -*- encoding : utf-8 -*- require 'spec_helper' describe GroupType do it_should_validate_presence_of :description it "should be ordered by order field" do types = [2, 3, 1, 3, 4].collect { |n| GroupType.new(priority: n) } types.sort.collect(&:priority).should == [1, 2, 3, 3, 4] end end
# code here! class School def initialize(name) @name = name @roster = {} end def roster @roster end def add_student(name,grade) if @roster.has_key?(grade) @roster[grade] << name else @roster[grade] = [name] end end def grade(year) @roster[year] end def sor...
module Refinery module Caststone class Column < Refinery::Caststone::Component has_many :compatibles, foreign_key: :component_id has_many :products, through: :compatibles, inverse_of: :columns end end end
require 'spec_helper' describe 'Facter::Util::Fact' do version_matrix = { 'OpenSSH_5.1p1, OpenSSL 0.9.8a 11 Oct 2005' => { ssh_version: 'OpenSSH_5.1p1', ssh_version_numeric: '5.1' }, # SLES 10.4 i586 'OpenSSH_5.1p1, OpenSSL 0.9.8j-fips 07 Jan 2009' => { ssh_version: 'OpenSSH_...
class SubcommentLife < ActiveRecord::Base belongs_to :user belongs_to :comment_life end
class String define_method(:title_case) do non_cap_words = ["the", "and", "of", "or", "from", "but", "to", "on"] split_sentence = self.downcase().split() split_sentence.each() do |word| if !non_cap_words.include?(word) || split_sentence.index(word) == 0 word.capitalize!() end end ...
class UsersController < ApplicationController # before_action 処理が実行される直前に、特定のメソッドを実行する。 # editとupdateだけ、先にlogged_in_userを実行 # ログインしないでアクセスした時 before_action :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers] # editとupdateだけ、正しいユーザーかどうか確認 before_action :correct_user, only: [:e...
require 'rails' require 'shellwords' module MongoidReactScaffold module Generators class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def copy_data_former copy_file "data_former.rb", "app/models/data_former.rb" copy_file "data_f...
class Api::V1::TransactionsController < ApplicationController before_action :set_student, only: [:index] # This method will be invoked from multiple locations. # If no student_id has been provided in the route, then return ALL transactions # If a student_id has been provided in the route, then return all of a # ...
module Base class Event include Value def initialize(id:) @id = id end end end
# == Schema Information # # Table name: follows # # user_id :integer # following_id :integer # created_at :datetime not null # updated_at :datetime not null # class Follow < ApplicationRecord belongs_to :user, class_name: "User" belongs_to :following, class_name: "User" end
require 'test_helper' class Setting::LanguageesControllerTest < ActionDispatch::IntegrationTest setup do @setting_languagee = setting_languagees(:one) end test "should get index" do get setting_languagees_url assert_response :success end test "should get new" do get new_setting_languagee_ur...
class CreateJoinTableParticipations < ActiveRecord::Migration[5.2] def change create_join_table :events, :users, table_name: 'participants' do |t| t.index :event_id t.index :user_id t.index [:event_id, :user_id], unique: true # t.index [:user_id, :event_id] end end end
class Movie < ActiveRecord::Base def self.total_runtime_in_minutes Movie.sum(:run_time_in_minutes) end end
module Inventory class ItemTransaction include Mongoid::Document include Mongoid::Timestamps::Short include ConvertQuantity field :plant_id, type: BSON::ObjectId # might be removed if no ID assigned # TODO: Create index for ref_id + ref_type field :ref_id, type: BSON::ObjectId field...
class Recipe < ActiveRecord::Base has_many :ingredients has_many :foods, :through => :ingredients belongs_to :user validates :name, :length => { :maximum => 140} validates_presence_of :serves end # == Schema Information # # Table name: recipes # # id :integer not null, primary key # name ...
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'Versions', type: :request, versioning: true do describe 'POST /revert' do let(:this_case) { FactoryBot.create(:case) } before do this_case.update!(blurb: "A new blurb") version_id = this_case.versions[-1].id post "/cases...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :ques_and_an, :class => 'QuesAndAns' do question "MyText" answer_type 1 answer_choices "" right_answer "" mock_test nil creator nil end end
class Friendship < ActiveRecord::Base belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id' belongs_to :user before_update :set_inverse_relation after_destroy :delete_inverse_relation paginates_per 15 def set_inverse_relation if self.is_confirmed_changed? && self.is_confirmed F...
json.array!(@adoption_requests) do |adoption_request| json.extract! adoption_request, :id json.url adoption_request_url(adoption_request, format: :json) end
class Api::VersionsController < ApplicationController respond_to :json def create part = Part.find(params[:version].delete(:part_id)) respond_with(:api, part.cut_version!) end end
require "spec_helper" describe User do before do @user = FactoryGirl.create :user @favorite = FactoryGirl.create :favorite, :user => @user end it "should create with OmniAuth data" do user = User.create_with_omniauth({ "provider" => "github", "uid" => 99, "info" => { "nick...
Gem::Specification.new do |s| s.name = 'jester-os' s.version = '0.0.1' s.date = '2019-10-01' s.summary = "jEstEr operating system" s.description = "Web-based, operating on the cloud platform: Dockerized, GDPR-compliant, 3D-Ready" s.authors = ["KOMA"] s.email = 'manu@korfman...
#! /usr/bin/env ruby require 'net/ntp' class NetTime attr_accessor :server def initialize(server) self.server = server || 'us.pool.ntp.org' end def response @response ||= Net::NTP.get server end def time response.time end def print_info puts "Time is: #{response.time}\n\n" puts "...
require File.expand_path("../helper", __FILE__) describe 'LocalwikiClient' do before(:all) do VCR.insert_cassette 'list', :record => :new_episodes @wiki = Localwiki::Client.new ENV['localwiki_client_server'], ENV['localwiki_client_user'], E...
class CreateForumTopicLanguages < ActiveRecord::Migration def up create_table :tr8n_forum_topic_languages do |t| t.integer :language_id t.integer :topic_id t.timestamps end add_index :tr8n_forum_topic_languages, [:language_id], :name => :tr8n_toplang end def down drop_table :tr...
require 'spec_helper' require 'kaede/channel' require 'kaede/database' require 'kaede/syoboi_calendar' require 'kaede/updater' describe Kaede::Updater do let(:db) { Kaede::Database.new(DatabaseHelper.database_url) } let(:syobocal) { Kaede::SyoboiCalendar.new } let(:updater) { described_class.new(db, syobocal) } ...
class ArticlesController < ApplicationController before_action :signed_in_user, only: [:create, :destroy] $id def index @article = Article.find(params[:id]) end def new @article = Article.find(params[:id]) end def show @article = Article.find(params[:id]) store_article_id @article.id @user = Use...
class GameObjectsController < ApplicationController protect_from_forgery only: [] before_action :set_game_object before_action :authenticate_user! after_action :publish_game_object def show @game_object = GameObject.find(params[:id]) render json: {game_object: @game_object.game_json} end def update if @g...
class FontInknutAntiqua < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/inknutantiqua" desc "Inknut Antiqua" homepage "https://fonts.google.com/specimen/Inknut+Antiqua" def install (share/"fonts").install "InknutAntiqua-Black.ttf" ...
# # Author:: Celso Fernandes (<fernandes@zertico.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Softlayer class DNS class Mock def create_record(opts) new_record = { "id" => Fog::Mock.random_nu...
require 'cloudformation_mapper/resource' class CloudformationMapper::Resource::AwsPropertiesElasticacheSecurityGroup < CloudformationMapper::Resource register_type 'AWS::ElastiCache::SecurityGroup' type 'Template' parameter do type 'Template' name :Properties parameter do type 'String' ...
# -*- encoding: utf-8 -*- $:.push(File.expand_path("../lib", __FILE__)) require "zebra/version" Gem::Specification.new do |s| s.name = "zebra" s.version = Zebra::VERSION s.authors = ["Lucas Charles"] s.email = ["mail@lucascharles.me"] s.homepage = "http://lucascharles.me" s.summar...
ActiveAdmin.register Review do permit_params :name, :stars, :description, :status config.per_page = 10 menu :priority => 5 actions :all, :except => [:show] filter :stars filter :name filter :status, as: :select, collection: Review::STATUS_TYPES scope "Все", :all, :default => true scope "Показать"...
class DesignVersion < ActiveResourceRecord self.site = "#{Figaro.env.locate_design_app}/api/v1" belongs_to :design belongs_to :visual end
class SetDefaultValueForFavorite < ActiveRecord::Migration[5.1] class Cipher < ActiveRecord::Base; end def change change_column_default :ciphers, :favorite, false change_column_null(:ciphers, :favorite, false, false) end end
require 'rubygems' require 'nokogiri' require 'open-uri' class MyCrawler def initialize() @total_input = 0 end def get_input_count(url, depth=3, page_limit = 50) next_urls = [url] already_visited = {} current_page_hrefs = [] depth.times do |n| break if next_urls.empty? ...
require "minitest_helper" require "English" class ExeTest < Minitest::Test def test_chandler_is_executable_and_exits_with_success within_project_root do Bundler.with_clean_env do output = `bundle exec chandler --version` assert_equal("chandler version #{Chandler::VERSION}\n", output) ...
json.array!(@seat_prices) do |seat_price| json.extract! seat_price, :id, :theater_id, :weekdays, :weekdays, :weekends, :weekends, :is_deleted json.url seat_price_url(seat_price, format: :json) end
desc "Create time log" # NOTE: Call this using heroku run rake 'create_time_log[C18]' -a cannected-beta # Assign time long to task of specific batch, using batch_no as param task :create_time_log, [:batch_no] => :environment do |t, args| args.with_defaults(:batch_no => "B01") pp "Generate timelog for #{args.batc...
class Bs::Elawa::Segment < ActiveRecord::Base belongs_to :event has_many :performances, class_name: 'SegmentPerformance' has_many :performers, through: :performances validates :event, presence: true validates :name, presence: true end
class AddEstadoToIdeas < ActiveRecord::Migration def change remove_column :ideas, :estado add_reference :ideas, :estado, index: true, foreign_key: true end end
class DiscussionChannel < ApplicationCable::Channel def subscribed stream_from 'discussion_channel' end def unsubscribed # Any cleanup needed when channel is unsubscribed end def chat(message) message = Message.create(text: message['text'], user_id: message['user_id']) message_partial = Appl...
# frozen_string_literal: true FactoryBot.define do factory :location_connection_step, class: 'Location::Connection::Step' do elvanto_form_id { 'MyString' } mail_chimp_user_id { 'MyString' } mail_chimp_audience_id { 'MyString' } content { 'MyText' } step { nil } location { nil } end end
class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:last_name, :first_name, :last_name_kana, :first_name_kana, :email, :business_type, ...
class GroupsController < ApplicationController before_filter :login_required before_filter :load_group,:only=>[:edit,:update,:show,:members,:destroy] before_filter :check_group_access, :only=>[:members,:show] before_filter :check_group_edit_access, :only=>[:edit,:update,:destroy] filter_access_to :all def ...
# == Schema Information # # Table name: posts # # id :integer not null, primary key # user_id :integer not null # post_body :text not null # post_title :string(255) not null # created_at :datetime # updated_at :datetime # twitter_url :string(255) # tweet_uid ...
# == Schema Information # # Table name: photos # # id :integer not null, primary key # caption :string default("") # user_id :integer not null # created_at :datetime not null # updated_at :datetime not null # image_f...
Rails.application.routes.draw do resources :prizes, only: [:index] resources :prize_categories resources :messages resources :raffles do post '/draw_raffle', to: 'raffles#draw_raffle' resources :winners resources :numbers, only: [:index, :create, :destroy] resources :prizes, only: [:index, :new...
module API class App < Grape::API version 'v1', using: :header, vendor: 'api-grape-seed' format :json prefix :api resource :api_grape_seed do get do { test_endpoint: true } end end end end
require "rails_helper" RSpec.describe WasteExemptionsShared::OrganisationType::LimitedCompany, type: :model do describe "#name" do context "when fields_being_updated does not contain :name" do it { is_expected.to_not validate_presence_of(:name) } end context "when fields_being_updated contains :nam...
# coding: utf-8 class CommentsController < ApplicationController def create @comment = current_user.comments.build(content: comment_params[:content], music_id: params[:id]) if @comment.valid? && @comment.save flash[:success] = "コメントを投稿しました!" redirect_to music_url(@comment.music.id) else ...
FactoryBot.define do # factory :character do # sequence :fullname do |n| # "character_#{n}" # end # display_name { "#{fullname} displayed" } # prefixes "ch,Ch,CH" # css_color "#FFFFFF" # avatar nil # # factory :user_character do # association :creator, factory: :user, usernam...
class MeasurementSerializer < ActiveModel::Serializer attributes :id, :value, :date, :user, :measure_category_id belongs_to :measure_category belongs_to :user end
# encoding: utf-8 class VerifyForm VERIFY_PHOTO_PATH = File.join(Rails.root, "app/assets","verify_files") include Virtus extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Validations attribute :identify_card, String attribute :description, String attribute :identify_pho...
module Subdomain class Api class << self def matches?(request) if Rails.env.production? request.subdomain == 'api' else request.subdomain.blank? end end def path 'api' unless Rails.env.production? end end end end
# frozen_string_literal: true require 'active_record' require 'active_record/schema_dumper' module Tasks # Database class Database class << self def establish_connection(config) ActiveRecord::Base.establish_connection(config) end def create_database! ActiveRecord::Base.conne...
class Answer < ActiveRecord::Base belongs_to :taken_survey belongs_to :question belongs_to :possibility validates :possibility, presence: :true end
require 'json' require 'net/http' require 'net/https' require 'uri' require 'csv' require 'savon' require 'nexpose_ticketing/nx_logger' # Serves as the Remedy interface for creating/updating issues from # vulnelrabilities found in Nexpose. class RemedyHelper attr_accessor :remedy_data, :options, :log, :c...
class VisitGroupsController < ApplicationController respond_to :json, :html before_action :find_visit_group, only: [:update, :destroy] def new @current_page = params[:current_page] # the current page of the study schedule @protocol = Protocol.find(params[:protocol_id]) @visit_group = VisitGroup....
class Comment < ApplicationRecord belongs_to :user belongs_to :doubt validates_presence_of :user, :doubt, :description end
require 'test_helper' class Auth::Panel::AuthorizedTokensControllerTest < ActionDispatch::IntegrationTest setup do @authorized_token = auth_authorized_tokens(:one) end test 'index ok' do get url_for(controller: 'auth/panel/authorized_tokens') assert_response :success end test 'edit ok' do g...
class User < ApplicationRecord has_secure_password has_many :song_lists has_many :jukebox_lists has_many :song_list_songs, through: :song_lists has_many :jukebox_list_songs, through: :jukebox_lists end
# Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: # # set :cron_log, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some...
require_relative '../app/paper' describe Paper do let(:paper) {Paper.new} it "should have a name" do expect(paper.name).to eq("Paper") end it "should beat rock" do expect(paper.beat_rock).to be true end it "should beat spock" do expect(paper.beat_spock).to be true end it "shouldn't beat scissors" d...
class Athelete < ActiveRecord::Base has_many :itri_records, class_name: "ItriRecord",foreign_key: :owner_id belongs_to :unit end
class HTMLReport # Initialize the report class def initialize() @overallResult = 'PASS' @reportContent1 = '' @reportContent2 = '' @start_time = Time.now @passed = 0 @failed = 0 end def createReport(reportName, header, browser_type) @reportName = reportName def get_date ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable # Setup accessible (or protected) attri...
#encoding: utf-8 class Material < ActiveRecord::Base has_many :prod_mat_relations has_many :mat_order_items has_many :mat_out_orders has_many :mat_in_orders has_many :prod_mat_relations STATUS = {:NORMAL => 0, :DELETE => 1} TYPES_NAMES = {1 => "施工耗材",2 => "辅助工具", 3 => "劳动保护", 4 =>"一次性用品", 5=>"产品"} TYP...
class Player < ActiveRecord::Base belongs_to :team has_many :cards def name "#{last_name}, #{first_name} " end def as_json(options = {}) super(:only => [:id], :methods => :name) end end
#!/usr/bin/env ruby require 'orocos' require 'rock/bundle' require 'readline' require 'optparse' #require 'vizkit' include Orocos # Command line options for the script, default values options = {:bb2 => true, :bb3 => true, :v => false} # Options parser OptionParser.new do |opts| opts.banner = "Usage: start.rb [opt...
class RemoveCounterColumnFromQuizTrial < ActiveRecord::Migration[5.0] def change remove_column :quiz_trials, :questions_count, :integer, null: false remove_column :quiz_trials, :correct_answers_count, :integer end end
require 'rails_helper' require "validates_email_format_of/rspec_matcher" describe Guard do it { should validate_email_format_of(:email).with_message('does not appear to be a valid e-mail address') } end RSpec.describe Guard, :type => :model do subject { described_class.new(first_name: "Oleg", last_name: "Chursi...
# Used to prepare text before sending it to the main analysis. # For now, just used to strip tags and punctuation class TextPreprocessor attr_accessor :text def initialize(text) @text = text end # quick way to perform multiple operations def perform(operations = []) operations.each do |operation| ...
class AdminArticleController < ApplicationController # GET /articles def index @articles = [] Article.order(:updated_at).each do |article| @articles << article end end # GET /articles/:article_id def show article_id = get_article_id @article = Article.find(article_id) @category ...
Rails.application.routes.draw do resources :products, param: :barcode, defaults: { format: :json } do collection do get "count" get "random" end end end
class AddRegionComunaToCrime < ActiveRecord::Migration[6.0] def change add_column :crimes, :region, :string add_column :crimes, :comuna, :string end end
class RemoveNameFromNewsletter < ActiveRecord::Migration[5.0] def change remove_column :newsletters, :name, :string end end
# create files for your ruby classes in this directory require 'pry' class Bakery attr_reader :name @@all = [] def initialize(name) @name = name @desserts = [] @@all << self end def self.all @@all end def average_calories sum = 0.0 average...
class SenderEmail < ActiveRecord::Base belongs_to :incoming_email validates_presence_of :incoming_email_id validates_presence_of :email validates_length_of :email, :within => 6..120 #r@a.wk validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_messag...
require 'rails_helper' RSpec.describe LearningDynamic, type: :model do it 'creates dynamics' do dynamic = build(:learning_dynamic) expect(dynamic).to be_valid end describe 'clone dynamics' do before(:each) do @orig = build(:learning_dynamic) @orig.set_status(:published) end it 'c...
# frozen_string_literal: true module Dry module Logic module Operations class Key < Unary attr_reader :evaluator attr_reader :path def self.new(rules, **options) if options[:evaluator] super else name = options.fetch(:name) e...
class UserServer < ApplicationRecord validates :user_id, :server_id, presence: true validates_uniqueness_of :user_id, :scope => [:server_id] belongs_to :user belongs_to :server end
require "reform" module Demo::Contract class Form < Reform::Form include Reform::Form::ActiveModel property :email validates :email, presence: true validates_uniqueness_of :email end end
require 'rails_helper' describe "the signin process", :type => :feature do let(:user) { FactoryGirl.create(:valid_user)} it "signs me in" do visit '/sessions/new' fill_in 'Email', :with => user.email fill_in 'Password', :with => user.password click_button "Log In" expect(current_path).to...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'rspec_metric_fu/version' Gem::Specification.new do |spec| spec.name = "rspec_metric_fu" spec.version = RspecMetricFu::VERSION spec.authors = ["Nick Thomas"] spec.emai...
class RecapDailyList include Mongoid::Document include Mongoid::Timestamps TYPE = ['Job'] field :type embedded_in :recap_daily belongs_to :job, inverse_of: nil belongs_to :recruitment, inverse_of: nil end
require 'rails_helper' describe 'User can delete a job' do scenario 'user clicks delete on a job page' do category = Category.create!(name: 'Test Category') company = Company.create!(name: 'ESPN') job = company.jobs.create!(title: 'Developer', level_of_interest: 70, city: 'Denver', category_id: category....
Rails.application.routes.draw do resources :review_houses devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations", confirmations: "users/confirmations", passwords: "users/passwords", :omniauth_callbacks => "users/omniauth_callbacks" } devise_scope :user do post "use...
require 'flowster/state' require 'flowster/transition' require 'flowster/preconditions' require 'flowster/hooks' module Flowster class Workflow def initialize(name, &workflow_definition) @name = name @states = {} @transitions = {} @preconditions = {} @hooks = { before: {}, after: {...
class BooksController < ApplicationController def index if params[:liked] == 'self' @title = 'Your Books Profile' @books = current_user.books else @books = Book.all end end def featured @followees = current_user.followees end def show @book = Book.find_by(id: params[:id]) @number_of_likes =...
# frozen_string_literal: true require "rails_helper" describe RepositoryType do describe "fields" do subject { described_class } it { is_expected.to have_field(:id).of_type(!types.ID) } it { is_expected.to have_field(:type).of_type("String!") } it { is_expected.to have_field(:re3dataId).of_type(typ...
require 'helpers/menu' require 'types/record' RSpec.describe Menu do describe '#show_waiting' do it 'without custom message' do expect(STDOUT).to receive(:puts).with('Чтобы продолжить нажмите ENTER...') allow($stdin).to receive(:gets).and_return('') Menu.show_waiting end it 'with custo...
# coding: utf-8 lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'method_argument_constraints/version' Gem::Specification.new do |spec| spec.name = "method_argument_constraints" spec.version = MethodArgumentConstraints::VERSION spec.authors...
require 'rails_helper' RSpec.describe Api::V1::VersionsController, type: :controller do render_views describe '#show' do let!(:versions) { create_list(:version, 2) } it 'render json of last version' do get :show expect(response).to have_http_status(200) expect(json_response[:version][:i...
module FriendlycontentApi class Client def self.download(source_info, path, opts={}, cont_default='') url = build_url source_info, path, opts p = build_query_params source_info, path, opts response = HTTParty.get(url, :query => p) if response.code!=200 raise 'cannot get file...
class RenameNameColumnToChats < ActiveRecord::Migration[5.2] def change rename_column :chats, :name, :message end end
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...