text
stringlengths
10
2.61M
class AddCoordinatesToRegion < ActiveRecord::Migration def change add_column :regions, :coords_lat, :string add_column :regions, :coords_long, :string end end
# frozen_string_literal: true require "spec_helper" module Decidim module Participations describe ParticipationsController, type: :controller do routes { Decidim::Participations::Engine.routes } let(:user) { create(:user, :confirmed, organization: feature.organization) } let(:params) do ...
require 'capcoauth/rails/routes/mapping' require 'capcoauth/rails/routes/mapper' module Capcoauth module Rails class Routes module Helper def use_capcoauth(options = {}, &block) Capcoauth::Rails::Routes.new(self, &block).generate_routes!(options) Capcoauth.configuration.using_ro...
class Hobby < ActiveHash::Base self.data = [ { id: 1, name: '--' }, { id: 2, name: '登山/トレッキング' }, { id: 3, name: '家庭菜園/ベランダ菜園' }, { id: 4, name: 'キャンプ/グランピング' }, { id: 5, name: 'ボルダリング' }, { id: 6, name: 'ヨガ' }, { id: 7, name: '将棋' }, { id: 8, name: '編み物' }, { id: 9, name: 'ひとり旅' }...
require 'mars_rovers/error' require 'mars_rovers/mars_plateu' require 'mars_rovers/rover' module MarsRovers module FileParser class << self def parse!(path) if File.exists?(path) result = { rovers: [], } begin File.open(path) do |f| ...
#require 'builder' class PayrollResultsExporter attr_reader :employer_name attr_reader :employee_dept attr_reader :employee_name attr_reader :employee_numb attr_reader :payroll_names attr_reader :payroll_config attr_reader :payroll_period attr_reader :payroll_result def initialize(company, departmen...
require 'test_helper' require 'libsvm' require 'libsvm/node' class PredictionTest < ActiveSupport::TestCase PATH_TO_TRAIN_DATA = "/training_data/training_data.csv" PATH_TO_TRAINED_MODEL = "/training_data/svm_trained_model.csv" test "should not save prediction without height and weight" do prediction = Pred...
class Api::V1::MaintenanceTasksController < ApplicationController skip_before_action :verify_authenticity_token before_action :restrict_access_if_no_api_key def create @maintenance_task = MaintenanceTask.new(maintenance_task_creation_params) @maintenance_task.status = "open" @maintenance_task.zip_id ...
#GET request get '/sample-4-how-to-download-a-file-from-groupdocs-storage-using-the-storage-api' do haml :sample04 end #POST request post '/sample-4-how-to-download-a-file-from-groupdocs-storage-using-the-storage-api' do #Set variables set :client_id, params[:clientId] set :private_key, params[:privateKey] s...
#le routeur a pour but de laisser 3 choix à l'utilisateur # 1 Créer un Gossips # 2 Voir la listes des Gossips # 3 Supprimer un Gossip en particulier. require_relative 'controller' class Router def initialize @controller = Controller.new @view = View.new end def perform puts "BIENVENUE DANS THE GOSS...
class Api::V1::BaseController < ApplicationController include Authenticable respond_to :json before_action :authenticate! private def authenticate! authenticate_token || render_unauthorized end def authenticate_token authenticate_with_http_token do |token, options| User.where(auth_token...
class Course < ApplicationRecord belongs_to :university has_many :majors end
# frozen_string_literal: true # mixin our library class Chef::Recipe include Provision end # note that opennms needs to be running for provisioning commands to work # as they use the ReST interface. log 'Start OpenNMS to perform ReST operations.' do notifies :start, 'service[opennms]', :immediately end # minimal op...
require 'vanagon/utilities' require 'vanagon/logger' class Vanagon class Component class Source class Local attr_accessor :url, :file, :extension, :workdir, :cleanup # Extensions for files we intend to unpack during the build ARCHIVE_EXTENSIONS = { "7z" => %w[.7z], ...
require 'fastlane/action' require_relative '../helper/git_helper' require_relative '../helper/encrypt' module Fastlane module Actions class FlintSetupAction < FlintAction def self.run(params) containing = FastlaneCore::Helper.fastlane_enabled_folder_path path = File.join(conta...
class AddDetailsToListings < ActiveRecord::Migration def change add_column :listings, :website, :string add_column :listings, :is_remote, :boolean add_column :listings, :town, :string add_column :listings, :county, :string add_column :listings, :postcode, :string add_column :listings, :enabled...
class PSD::Image::Mode # Combines the channel data from the image into RGB pixel values module RGB private def combine_rgb_channel (0...@num_pixels).step(pixel_step) do |i| pixel = {r: 0, g: 0, b: 0, a: 255} PSD::Image::CHANNEL_INFO[0...channels].each_with_index do |chan, index| ...
class ClubRegistrationsController < ApplicationController # GET /club_registrations # GET /club_registrations.json def index @club_registrations = ClubRegistration.all respond_to do |format| format.html # index.html.erb format.json { render json: @club_registrations } end end # GET /...
class AcademicAbility include CanCan::Ability def initialize(current_academic) can :read, Project do |project| project.academic_id == current_academic.id end can :manage, Aprofile end end
require_relative "map" require_relative "connection" require_relative "edge" require "forwardable" class MapNode attr_accessor :connections, :position, :radius, :map, :uniqid extend Forwardable def_delegators :position, :x, :y def_delegators :map, :polygon, :base_angle @@id_count = 0 d...
Then(/^Due Date has to be in 'Month Day, Year' format$/) do if on(PaymentsDetailsPage).due_date != '(Pending first billing cycle)' expect(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']).to include on(PaymentsDetailsPage).due_date.split(" ...
# questo script permette di cambiare bersaglio di alcune abilità # da amico a nemico e viceversa. # Se un'abilità può cambiare bersaglio da nemico/amico, bisogna mettere # il tag <switchable> nelle note (definito negli attributi aggiuntivi) # # #==========================================================================...
class User < ApplicationRecord # refer: https://www.javatpoint.com/ruby-on-rails-session # has_secure_password has_one :address, dependent: :destroy validates :first_name, presence: true validates :last_name, presence: true validates :dob, presence: true validates :gender, presence: true validates :ema...
class Admin::ChaptersController < Admin::AdminController before_action :find_chapter, only: [:edit, :update, :show, :destroy] load_and_authorize_resource def index @chapters = Chapter.paginate page: params[:page], per_page: Settings.chapters.page end def show end def new @chapter = Chapter.new ...
class CardSerializer < ActiveModel::Serializer cached delegate :cache_key, to: :object attributes :id, :rank, :suit, :trick_id, :player_id end
class AddDeletedAtToAccountSettings < ActiveRecord::Migration def change add_column :account_settings, :deleted_at, :datetime end end
class ProductsController < ApplicationController def new @product = Product.new @product.discs.build @product.songs.build end def index @products = Product.page(params[:page]).per(15) @q = Product.ransack(params[:q]) @products = @search_products @product_randoms = Product.order("RAND...
class Admin::Attributes::ZonesController < ApplicationController before_filter :authenticate_admin before_filter :current_admin layout 'admin' def index @zones = PropertyAttrZone.order('sort').all end def show @zone = PropertyAttrZone.find(params[:id]) @current_admin = current_admin end d...
require 'test_helper' class AddressTest < ActiveSupport::TestCase setup do @address = addresses(:one) end test_fixtures test 'consignee should be present' do @address.consignee = ' ' assert_not @address.valid? end test 'mobile should be present and valid' do @address.mobile = ' ' ass...
module Svpply class Product attr_reader :id, :title, :price, :formatted_price, :currency_code, :discount, :discount_code, :category, :categories, :gender, :image, :image_height, :image_width, :saves, :notes, :status_id, :date_created, :date_updated, :url, :svpply_url, :store def self....
require_relative 'contacts' # Interfaces between a user and their contact list. Reads from and writes to standard I/O. class ContactList # TODO: Implement user interaction. This should be the only file where you use `puts` and `gets`. puts "Here is a list of available commands: new - create a new contact...
namespace :deploy do desc '顯示目前部署的版本。' task :revision do on roles(:app) do execute "cat #{current_path}/REVISION" end end desc '確認本機端程式版本與遠端一致。' task :revision_checker do unless `git rev-parse develop` == `git rev-parse origin/develop` && `git rev-parse master` == `git rev-parse origin/mas...
namespace :pmi do desc 'read user credentials from PMI registry' task get_credentials: :environment do puts 'updating...' Services::PageGetter.new.call puts 'done.' end end
require 'set' # super reduced string def super_reduced_string(s) stack = [] s.chars.each do |ch| ch == stack.last ? stack.pop : stack.push(ch) end stack.empty? ? 'Empty String' : stack.join end ## camel case def camel_case_count(s) 1 + s.chars.count { |ch| ch == ch.capitalize } end # two characters de...
require 'spec_helper' describe WebstopApi::Configuration do describe '.api_key' do it 'should return default key' do WebstopApi.api_key.should == WebstopApi::Configuration::DEFAULT_API_KEY end end describe '.format' do it 'should return default format' do WebstopApi.format.should == Web...
class PostsController < ApplicationController def index page = params[:page] #12345567...,nil if page == nil page = 1 end @page = page.to_i #to_iは、文字列を受けとってコピーして整数にして返す。非破壊的メソッド @page_num = 5#1ページに表示したいやつ @record_count = Post.where("id > 0").count @posts = Post.all.order(created_...
# == Schema Information # # Table name: users # # id :bigint(8) not null, primary key # first_name :string # last_name :string # gender :integer # character :integer # email :string default(""), not null # ...
module ROXML module XML # ::nodoc:: Document = REXML::Document Node = REXML::Element class Node class << self def new_cdata(content) REXML::CData.new(content) end def new_element(name) name = name.id2name if name.is_a? Symbol REXML::Element.new...
# frozen_string_literal: true module RGrid # Raised when {RGrid::Validator} # # @api private # class InvalidGrid < StandardError # Returns the default error message unless a message was given # when raising. # # @return [String] def message 'Grid cannot be created as parameters ar...
class User < ApplicationRecord has_secure_password has_secure_token :email_confirmation enum role: %i[student teacher administrator] scope :with_token, ->(token) { where(email_confirmation: token) } scope :with_role, ->(role) { where(role: role) if role.present? } end
require 'rails_helper' RSpec.describe 'listing products' do it 'displays list of products' do c = Category.create(name: "Footwear") c.products.create(name: "Shoe", description: "Walking", price: 10.00) visit "/" expect(page).to have_text("Shoe") expect(page).to have_text("Footwear") expect(page).to have_t...
require 'rails_helper' RSpec.describe 'Invoice Factory' do describe 'invoice_new' do describe 'default' do it('is valid') { expect(invoice_new).to be_valid } it 'makes a invoice_text' do expect { invoice_new }.to change(InvoiceText, :count).by(1) end end describe 'override' do...
Rails.application.routes.draw do root "categories#index" resources :users, only: [:new, :create, :show] resources :ideas resources :categories resources :images get "/signup", to: 'users#new' delete "/logout", to: 'sessions#destroy' get "/login", to: 'sessions#new' post "/login", to: 'ses...
class Transfer attr_accessor :name, :sender, :transfer, :receiver, :status, :amount def initialize(name, sender, transfer) @name = sender @sender = name @receiver = sender @status = "pending" @amount = transfer #binding.pry end def valid? @sender.balance == 1000 && @receiver.bal...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "alarm#index" resources :alarm get 'alarm/time', to: 'alarm#time' end
class User < ApplicationRecord has_many :created_events, :foreign_key => "creator_id", :class_name => "Event" has_many :attended_events, :through => :invitations, :class_name => "Event" has_many :invitations, :foreign_key => "attendee_id" end
class Player attr_accessor :piece, :name #we make the instance variables, piece and name, readable and writable def initialize(num, name) #we are settig up an internal variable, piece, in the class Player @piece=num #the piece variable is defined as the player number, either 1 or 2 end #Takes players move which...
class AddFileCodeToDefile < ActiveRecord::Migration def change add_column :defiles, :filecode, :string end end
require 'rails_helper' RSpec.describe "Agent signs in", type: :request do include Warden::Test::Helpers include ApiHelpers before(:all) do # Create agent @agent = FactoryGirl.create :agent expect(@agent).to be_present expect(@agent.network).to be_present # Check user created @...
class AddmachineSpecificWare < ActiveRecord::Migration[5.2] def change add_column :wares, :machine_specific, :boolean end end
module PageFoldersHelper def entry_path(entry, type) case type when :folder page_folder_path entry when :page page_path entry end end def entry_icon(type) case type when :folder glyphicon 'folder-open' when :page glyphicon 'file' end end end
class FuelStocksController < ApplicationController before_action :set_fuel_stock, only: [:show, :edit, :update, :destroy] # GET /fuel_stocks # GET /fuel_stocks.json def index @fuel_stocks = FuelStock.all end # GET /fuel_stocks/1 # GET /fuel_stocks/1.json def show end # GET /fuel_stocks/new ...
require './helpers/persistence_handler' require './helpers/file_system_manager' require './helpers/vagrant_control' class Machine_Delete def initialize @persistence_handler = PersistenceHandler.new @file_system_manager = FileSystemManager.new @vagrant_control = VagrantControl.new end def delete_fo...
module Admin::InnovateApplicantsHelper def lang_to_human(lang) mappings = { javascript: "JavaScript", ruby: "Ruby", python: "Python", php: "PHP", java: "Java", cplus: "C++", csharp: "C#" } mappings[lang.to_sym] end def innovate_order_by_to_human(order_by) ...
# frozen_string_literal: true module Diplomat # Methods for interacting with the Consul dataceneter API endpoint class Datacenter < Diplomat::RestClient @access_methods = [:get] # Get an array of all avaliable datacenters accessible by the local consul agent # @param meta [Hash] output structure conta...
class UserUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: include CarrierWave::RMagick # include CarrierWave::MiniMagick # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility: # include Sprockets::Helpers::RailsHelper # include Sprockets::Helpers::Isolate...
class ConvertHandler def handle(parameters) amount = parameters.first.delete(' ') if parameters.first == 'help' return "Oh, Sorry! I don't understand *help convert #{parameters.first}*. Type `/csbot help` for available commands" end if amount =~ /[[:alpha:]]/ return 'Ou, sorry! I cannot p...
class CreateOauthtokens < ActiveRecord::Migration[5.2] def change create_table :oauthtokens do |t| t.string :key t.string :access_token t.string :refresh_token t.string :scope t.string :state t.string :token_type t.integer :user_id t.timestamp :expires t.time...
# -*- mode: ruby -*- # # vi: set ft=ruby : require 'fileutils' Vagrant.require_version ">= 1.6.0" $cloud_config_path = File.expand_path("./user-data", File.dirname(__FILE__)) $config_path = File.expand_path("./config.rb", File.dirname(__FILE__)) # Defaults for config options defined in CONFIG $update_channel = "alp...
require 'rails_helper' RSpec.describe Post, :type => :model do it "should have title" do expect((build :post, {:title => nil}).valid?).to be false expect((build :post, {:title => ''}).valid?).to be false end it "should have link" do expect((build :post, {:link => nil}).valid?).to be false expect...
require_relative 'rotator' require_relative 'offset' class Encrypt attr_reader :character_map, :encrypted_message, :rotator, :offset, :key def initialize(rotator = Rotator.new) @character_map = character_map @encrypted_message = [] @rotator = rotator @offset = Offset.new @key = generate_key ...
require "rails_helper" RSpec.describe LandlordsController, type: :routing do describe "routing" do it "routes to #index" do expect(get: "/landlords").to route_to("landlords#index") end it "routes to #new" do expect(get: "/landlords/new").to route_to("landlords#new") end it "routes t...
class OneOff::CphcEnrollment::DiabetesDiagnosisPayload attr_reader :blood_sugar, :encounter_id def initialize(blood_sugar, encounter_id) @blood_sugar = blood_sugar @encounter_id = encounter_id end def payload medical_history = blood_sugar.patient.medical_history {"encounterId" => encounter_id,...
class GuestUser < ApplicationRecord def uniqname "guest_user" end end
require 'lib/helper_helpers' module StructuredDataHelpers def structured_data_markup [ person_structured_data, web_site_structured_data, article_structured_data, article_breadcrumbs_structured_data, index_summary_carousel_structured_data ].compact.map(&:to_json) .map do |mar...
class Users::PasswordsController < Devise::PasswordsController # PUT /users/password def update tos_accepted = resource_params[:tos_accepted] if tos_accepted != "1" flash[:alert] = 'Terms of service must be accepted.' respond_with(resource, location: edit_user_password_path(resource_params.sli...
class CreateImpression < ActiveRecord::Migration def change create_table :impression do |t| t.string :name t.integer :impression_count t.integer :user_id t.integer :paid_amount t.string :payment_type t.timestamps end end end
class ContactGroup < ActiveRecord::Base has_many( :contacts, primary_key: :id, foreign_key: :group_id, class_name: "Contact" ) end
class User < ApplicationRecord validates :name, presence: true, length: {minimum: 6}, uniqueness: {case_sensitive: true} validates :email, presence: true, uniqueness: {case_sensitive: false} has_secure_password validates :password, presence: true, length: {minimum: 6} end
# Override controller to add further functionality to Devise's standard # offerings. class RegistrationsController < Devise::RegistrationsController private # Returns the custom list of user params. # This method simply calls out to sign_up_params, because we actually # want both sets to be identical. def ac...
# # Send email # class Email < Vue def render _button.btn 'send email', class: self.mailto_class(), onClick: self.launch_email_client end # render 'send email' as a primary button if the viewer is the shepherd for # the report, otherwise render the text as a simple link. def mailto_class() if ...
class Serving < ActiveRecord::Base belongs_to :wine belongs_to :bottle_holder belongs_to :tag belongs_to :dispenser belongs_to :user validates :dispenser_id, :presence => true, :numericality => true validates :bottle_index, :presence => true, :numericality => true validates :price, :presence => :true validate...
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable audited has_many :login_activities, as: :user devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable ...
class Ability include CanCan::Ability # TODO Can we also say something like this: # can ..., user: user # ? def initialize(user) if user.present? if user.admin? can :manage, :all end can :create, Topic can [:update, :destroy], Topic, author_id: user.id can :cre...
class CreateIssues < ActiveRecord::Migration[5.1] def change create_table :issues do |t| t.integer :issuable_id t.string :issuable_type t.integer :author_id t.string :title, null: false t.text :body, null: false, default: "" t.timestamps end add_index :issues, [:i...
class RemoveAssessmentFromTasks < ActiveRecord::Migration def change remove_column :tasks, :assessment, :integer end end
class AddColumnGrade < ActiveRecord::Migration def change add_column(:periods_students, :grade, :string) end end
# frozen_string_literal: true require 'apartment/elevators/generic' module Apartment module Elevators # Provides a rack based tenant switching solution based on hosts # Uses a hash to find the corresponding tenant name for the host # class HostHash < Generic def initialize(app, hash = {}, ...
class Result < ApplicationRecord belongs_to :query def from_json @json ||= JSON.parse(self.text) end end
# frozen_string_literal: true class ApplicationController < ActionController::Base include UserSystem MEMBER_LAYOUT = 'dark_ritual' PUBLIC_LAYOUT = 'public' protect_from_forgery prepend: true, with: :exception layout -> { current_user ? MEMBER_LAYOUT : PUBLIC_LAYOUT } if Rails.env.production? befor...
class Program < ActiveRecord::Base has_many :room_program_time_maps has_many :rooms, :through => :room_program_time_maps end
module Users class CommentsController < ApplicationController load_and_authorize_resource :post load_and_authorize_resource :comment, through: :post # # POST /posts/1/comments # def create @comment = @post.comments.create(comment_params.merge(user_id: current_user.id)) if...
class Arena def initialize name @name = name @gladiators = [] end def name return @name.capitalize end def gladiators return @gladiators end def add_gladiator new_gladiator if @gladiators.length < 2 @gladiators << new_gladiator end end def fight if @gladiators.length...
require "test_helper" feature "Authentication Feature Test" do before do @user = FactoryGirl.create(:user) end scenario "Sign in and sign out" do visit root_url click_link "Sign in" current_path.must_equal new_user_session_path fill_in "user_email", with: @user.email fill_in "user_passw...
module DasMainMusic def initialize @emachine = CombiningMachine.new @emachine.name = "emachine" @eparser = LetterParser.new( @emachine ) @emachine.parser = @eparser @p2machine = CombiningMachine.new @p2machine.name = "p2machine" @p2parser = LetterParser.new( @p2machine ) @...
#!/usr/bin/env ruby require 'json' require 'time' require 'zlib' def statproc failed = 0 STDIN.each_line "\0", 65535 do |line| path = line.chomp "\0" begin stat = File.lstat path stat.directory? and path[-1] != '/' and path += "/" puts({ mtime: stat.mtime.gmtime.iso8601, path: path, st_size:...
require "rails_helper" RSpec.feature "Users can sign out" do after { logout } scenario "success" do # Given a user exists user = create(:administrator) # And is logged in authenticate!(user: user) # When they sign out visit root_path click_on "Sign out" # Then they should be logg...
require "jruby-pcap/packet" java_import java.sql.Timestamp module Jruby::Pcap class LiveHandle include Enumerable def initialize(interface) @interface = interface end def each handle = @interface.open_live(1024, PcapNetworkInterface::PromiscuousMode::PROMISCUOUS, 0) while true do...
class AdminLocation < ApplicationRecord belongs_to :user belongs_to :location end
class Restaurant < ActiveRecord::Base include Visitavel belongs_to :pais belongs_to :estado belongs_to :cidade belongs_to :user #Galleria has_many :restaurant_galleries accepts_nested_attributes_for :restaurant_galleries #logo has_attached_file :logo, styles: { medium: "300x300>", thumb: "100x...
class AddLinkRoleToDashBoard < ActiveRecord::Migration[5.2] def change add_column :dash_boards, :link_role, :string end end
class Messaging::AlphaSms::Sms < Messaging::Channel def self.communication_type Communication.communication_types[:sms] end def self.get_message_statuses AlphaSmsDeliveryDetail.where("created_at > ?", 2.days.ago).in_progress.find_each do |detailable| AlphaSmsStatusJob.perform_async(detailable.reque...
class PostValidator < ActiveModel::Validator def validate(post) if post.title != nil unless post.title.match?(/Won't Believe/) post.errors[:clickbait] << "No Clickbait Titles Allowed!" end end end end # Finally, add a custom validat...
class Shimekiri < ActiveRecord::Base belongs_to :worker, class_name: "User" belongs_to :owner, class_name: "User" end
# encoding : UTF-8 require 'rubygems' gem 'shoulda' require 'test/unit' require 'shoulda' require 'sitra_client/touristic_object' class TouristicObjectTest < Test::Unit::TestCase should 'populate title of touristic object' do hash_result = {:nom => {:libelleFr => "my_title"}} touristic_object = TouristicObj...
require 'wsdl_mapper/dom_parsing/default_resolver' module WsdlMapperTesting module TestHelper extend self def get_fixture(name) path = File.join ::TEST_FIXTURE_PATH, name File.read(path) end def get_xml_doc(name) Nokogiri::XML::Document.parse get_fixture name end def pars...
require 'delegate' module Gaudi::Configuration::SystemModules #System configuration parameters for the Unity unit testing framework module UnityConfiguration def self.list_keys [] end def self.path_keys ['unity_runner_generator'] end #Point this to the Ruby script Unity uses to cre...
FactoryGirl.define do factory :event do trait :processed do processed_at Time.now.midday end end end
module Downloader def self.table_name_prefix 'downloader_' end end
ActiveAdmin.register Contact do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # # permit_params :list, :of, :attributes, :on, :model # # or # # permit_params do # permitted = [:permitted, :attributes] # ...