text
stringlengths
10
2.61M
class Request < ApplicationRecord belongs_to :user has_many :conversations, dependent: :destroy validates :title, presence: true validates :description, presence: true, length: {maximum: 300} validates :latitude, presence: true validates :longitude, presence: true validates :request_type, p...
require 'spec_helper' describe CotizacionesPesoDolarHistoricoController do # This should return the minimal set of attributes required to create a valid # SaldoBancarioHistorico. As you add validations to SaldoBancarioHistorico, be sure to # update the return value of this method accordingly. def valid_attribu...
# frozen_string_literal: true # == Schema Information # # Table name: addresses # # id :bigint not null, primary key # city :string not null # country :string not null # line_one :string not null # line_two :string # postal_code :string # subdivi...
class Occurrence < ActiveRecord::Base belongs_to :objective belongs_to :user def mark_complete self.update_attributes({completed: true}) end end
class CreateBookings < ActiveRecord::Migration[5.0] def change create_table :bookings do |t| t.references :property, foreign_key: true t.references :contact, foreign_key: true end end end
class Invitation < ActiveRecord::Base include Tokenable belongs_to :sender, class_name: 'User', foreign_key: :sender_id belongs_to :receiver, class_name: 'User', foreign_key: :receiver_id before_create :generate_token validates :email, :name, presence: true validates :email, uniqueness: true end
class CreateGenes < ActiveRecord::Migration def change create_table :genes do |t| t.integer :suited t.text :gene t.integer :generation t.integer :in_generation_serial t.timestamps end end end
# frozen_string_literal: true RSpec.describe 'slide_types/edit', type: :view do let(:slide_type) { create(:slide_type) } before do assign(:slide_type, slide_type) render end it 'renders the edit slide_type form' do assert_select 'form[action=?][method=?]', slide_type_path(slide_type), 'post' do ...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :project do sequence(:name) { |n| "My Project #{n}" } client "My Client" archived false end end
module LogHelper def log(*messages, level: :info, separator: ', ') buffer = "[#{self.class.name}##{calling_method}]" buffer = "" if buffer == '[Object#block]' buffer << "(#{maybe_id})" if maybe_id buffer << " " buffer << messages.join(separator) Rails.logger.send(level, buffer) end def ...
require "test_helper" describe RentalsController do # before do # @customer = Customer.create(name: "Daenerys Targaryen", address: "some big house", registered_at: Date.parse("28 May 2020"), city: "Valyria", state: "Essos", postal_code: "98122", videos_checked_out_count: 2) # @video = Video.create(title: "Le...
module EasyPatch module WatchersControllerPatch def self.included(base) base.send(:include, InstanceMethods) base.class_eval do before_filter :get_available_watchers, :only => [:new, :autocomplete_for_user] skip_before_filter :find_project, :only => [:toggle_members] alias_...
# Your cPanel/SSH login name set :user , "shelahfi" # The domain name of the server to deploy to, this can be your domain or the domain of the server. set :server_name, "75.98.33.134" # Your svn / git login name set :scm_username, "shelah" #set :scm_password, Proc.new { CLI.password_prompt "Git Password: "} # Your r...
class FormMailer < ApplicationMailer default from: "jameson@aeroform.com" def form_email(data) @data = data puts(@data.to_yaml) mail(to: @data[:recipient], subject: "New form data!") end end
class CategoriesController < ApplicationController before_action :set_category, only: [:show, :update, :destroy] # GET /categories # shows nested places def index #Old default code for GET request @categories = Category.all #This code will provide a response to the GET request. #Here, the item...
# frozen_string_literal: true module ApiGuard VERSION = '0.5.2' end
require "test/unit" require "image_corrupter" class TestImageCorrupter < Test::Unit::TestCase # :nodoc: SCRIPT_DIR = File.expand_path(File.dirname(__FILE__)) IMAGE_TEST_FILE = "#{SCRIPT_DIR}/josh_forehead.jpg" IMAGE_TEST_START_BYTE = 741 IMAGE_TEST_CORRUPTION_FILE = "#{SCRIPT_DIR}/corruption_text_small.txt" ...
class CockDescriptionSeeds # Parameters used for batch descriptions # 1.0 - 3.9 inches - Tiny # 4.0 - 5.4 inches - Small # 5.5 - 6.9 inches - Average # 7.0 - 8.9 inches - Large # 9.0 - 11.9 inches - Huge # 12.0 - 14.9 inches - Massive # 15.0 - 23.9 inches - Monstrous # 24.0 - 29.9 inches - Gigantic ...
class AddUpdatedBooleanToComments < ActiveRecord::Migration def change add_column :comments, :updated, :boolean, :null => false, :default => :false end end
class CreateSearchConditions < ActiveRecord::Migration[5.2] def change create_table :search_conditions do |t| t.string :user t.string :shop_id t.text :keyword t.string :category_id t.string :store_id t.integer :min_price t.integer :max_price t.timestamps end ...
module Subject def initialize @observers = [] end def add_observer(observer) @observers << observer end def delete_observer(observer) @observers.delete(observer) end def notify_observers @observers.each do |observer| observer.update(self) end end end class Employee include Subject attr_read...
class OptimizedProductivity < ApplicationRecord belongs_to :store_department scope :between, ->(period) { where('date between ? AND ?', period[:start], period[:end]) } def avg_day hourly.values.map(&:to_i).sum / hourly.values.size end def self.by_date_hour(period) all.between(period).each_with_objec...
class Abavility < ActiveRecord::Base belongs_to :pharmacy belongs_to :medicine end
require 'net/http' require 'json' SLACK_API_URL = 'https://slack.com/api'.freeze class SlackAPIWrapper def initialize(bot_token) @bot_token = bot_token end def gen_url(endpoint) "#{SLACK_API_URL}/#{endpoint}" end def chat_post_message(text, channel) # https://api.slack.com/methods/chat.postMes...
module Fog module Compute class Google class Mock def delete_subnetwork(_subnetwork_name, _region_name) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end class Real ## # Delete a subnetwork. # # @param...
# # Author:: Ken-ichi TANABE (<nabeken@tknetworks.org>) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
class Time define_method(:sleep_in) do if self.monday?() return "Wake up, it's Monday!" elsif self.tuesday?() return "Wake up, it's Tuesday!" elsif self.wednesday?() return "Wake up, it's Wednesday!" elsif self.thursday?() return "Wake up, it's Thursday!" elsif self.friday...
class User < ApplicationRecord validates_uniqueness_of :uid, allow_blank: false validates :email, allow_blank: false, uniqueness: true, email: true has_many :workflow_accrual_jobs, :class_name => 'Workflow::AccrualJob' def netid self.uid.split('@').first end def net_id self.netid end def per...
# # 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...
Deface::Override.new( virtual_path: 'spree/layouts/admin', name: 'include_rich_text_js', insert_bottom: '[data-hook="admin_footer_scripts"]', text: '<%= render partial: "shared/rich_editor_javascript" %>' )
class PollOpinionsController < PollsController before_action :set_poll, only: %i[show edit update destroy] def new authorize PollOpinion @poll = PollOpinion.new( expiration_date: Date.today.weeks_since(2), owner_id: current_user.id ) 2.times { @poll.answers.build } end def create ...
namespace :db do def do_db_cmd(cmd,archive=nil) archive ||= ENV['FILE'] || Time.now.strftime("%Y%m%d-%H%M%S.sql") cmd << " > #{archive}" puts "With Rails.env=#{Rails.env}, running '#{cmd}'" result = system(cmd) raise("FAILED: #{$?}") unless result end desc "Dump DB corresponding to ENV[RAILS...
include ActionDispatch::TestProcess FactoryBot.define do factory :task do name { Faker::Name.unique.name } description { Faker::Lorem.sentence(word_count: 5) } user_id { create(:user).id } end end
class DefaultExpensesCreator include SuckerPunch::Job def perform(user_id) ActiveRecord::Base.connection_pool.with_connection do Expense.create_default_expenses_for(user_id) end end end
require 'rails_helper' require 'byebug' RSpec.describe Customize, type: :model do context 'database' do context 'columns' do it { should have_db_column(:file).of_type(:string) } it { should have_db_column(:installed).of_type(:boolean) } end end context 'class fuctions' do it { expect(Cu...
# encoding: UTF-8 # Copyright © Emilio González Montaña # Licence: Attribution & no derivates # * Attribution to the plugin web page URL should be done if you want to use it. # https://redmine.ociotec.com/projects/advanced-roadmap # * No derivates of this plugin (or partial) are allowed. # Take a look t...
require File.expand_path("test_helper", File.dirname(__FILE__)) require 'bigdecimal' require 'test/app_test_methods' class RubotoGenTest < Test::Unit::TestCase include AppTestMethods def setup generate_app end def teardown cleanup_app end def test_icons_are_updated Dir.chdir APP_DIR do ...
class DojoController < ApplicationController before_action :set_dojo, only: [:show, :edit, :update, :destroy] # ============================================ # GET Request - Renders root/home page [.html] # ============================================ def index # --- [ Put in Session ] session[:page]...
class ClerksessionsController < ClerkloginController skip_before_action :ensure_clerk_logged_in def new end def create clerk = Clerk.find_by(email: params[:email]) if clerk && clerk.authenticate(params[:password]) session[:current_clerk_id] = clerk.id redirect_to "/clerks" else ...
require 'rails_helper' feature 'add a bag' do context 'user is signed up' do scenario 'should diplay a notice saying no bags' do visit '/bags' expect(page).to have_link 'Add a bag' expect(page).to have_text 'No bags yet' end it "does not show bags on the index page" do visit '/bag...
# this list of function signatures was generated by the file # generate-ffi-ncurses-function-signatures.rb and inserted here by hand functions = [ [:COLOR_PAIR, [:int], :int], [:PAIR_NUMBER, [:int], :int], [:_nc_tracebits, [], :string], [:_nc_visbuf, [:string], :string], [:_trac...
class Api::SpacesController < Api::BaseController def index spaces = [] if current_user spaces += Space.by_user(current_user) end if params[:latitude].present? && params[:longitude].present? spaces += Space.published_nearby_to(params[:longitude].to_f, ...
require_relative 'sum' require_relative 'rest' require_relative 'multiplication' require_relative 'division' require_relative 'inverse' require_relative 'square_root' require_relative 'square' class Calculator OPERATIONS = { sum: '+', rest: '-', multiplication: '*', division: '/', inverse: 'INV', square: '...
class PasswordChangeForm < BaseForm attribute :user, User attribute :password, String attribute :password_confirmation, String validates :user, presence: true validates :password, presence: true, length: { within: 6..40 } validates :password_confirmation, presence: true validates_confirmation_of :passwor...
Rails.application.routes.draw do namespace :v1 do resources :product, only: [:create, :show], :format => false # TODO: :destroy & :update resource :products, only: [:show], :format => false end end
# frozen_string_literal: true # == Schema Information # # Table name: student_tags # # created_at :datetime not null # updated_at :datetime not null # student_id :integer not null # tag_id :uuid not null # # Indexes # # index_student_tags_on_student_id (student_id) # ind...
class MoviesController < ApplicationController def new @movie = @movie_entry.movies.build end def create # @movie = current_movie_entry.movies.build(movie_params) # if @movie.save # flash[:notice] = "Movie has been created." # redirect_to [@movie_entry, @movie] # else # flash[:...
class Post < ActiveRecord::Base belongs_to :user has_many :comments, :dependent => :destroy before_validation :generate_permalink before_save :save_html validates :permalink, uniqueness: true has_attached_file :image, :styles => { :large => "400x300>", :medium => "230x150>" }, :default_url => "/images/:s...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :air_booking do transaction nil arrival_date "2014-08-22 21:48:55" return_date "2014-08-22 21:48:55" destination_code "MyString" notes "MyString" end end
class Trailer include Mongoid::Document field :url, type: String field :name, type: String field :thumbnail, type: String field :original_thumbnail_url, type: String embedded_in :title mount_uploader :thumbnail, TrailerThumbnailUploader def fetch_thumbnail! return unless self.url puts('Fet...
require_relative 'tidy_number' describe TidyNumber do subject { TidyNumber.solve(number) } before { subject } context "when number = 1" do let(:number) { '1 ' } it { should eq 1 } end context "when number = 1111111110" do let(:number) { '1111111110' } it { shoul...
# Контроллер поиска # Ищется по названию в товарах # логика поиска мне не была дана class SearchController < Content::BaseController include ActionView::Helpers::TextHelper def search @query = params[:q].downcase @results = [] unless @query.empty? Good.with_translations.where('lower(title) like...
class CategoriesController < ApplicationController before_action :require_user, only: [:create] def index @categories = Category.all end def create @category = Category.create(category_params) if @category.save flash[:notice] = "Category added! Thank you." else flash[:danger] = "Err...
class Employee < ApplicationRecord has_many :leave_requests end
json.array!(@cheques) do |cheque| json.extract! cheque, :id json.url cheque_url(cheque, format: :json) end
require_relative 'test_helper' require_relative '../lib/transaction' class TransactionTest < Minitest::Test def setup @transaction_item = Transaction.new({ :id => 6, :invoice_id => 8, :credit_card_number => "4242424242424242", :credit_card_expirati...
feature 'ActiveAdmin' do let!(:premier) { create(:premier) } let!(:user) { create(:user) } describe 'premier login process' do it 'should login' do login_as_admin premier visit(admin_solicitudes_de_accesos_path) expect(current_path).to eql admin_solicitudes_de_accesos_path logo...
class Post < ApplicationRecord belongs_to :user has_many :taggings has_many :tags, through: :taggings enum category: { cat_one: 0, cat_two: 1 } validates :user, presence: true mount_uploader :images, ImageUploader def set_tags(names) self.tags = names.split(",").map do |name| Tag...
class BlogPostsListViewController < UIViewController POSTS_LIST_TAG = 1 def start(use_case) @use_case = use_case @handler = BlogPostsListHandler.new(self, use_case) @use_case.on_posts_fetched do |blog_posts| handler.provide_blog_posts(blog_posts) blog_posts_table_view.reloadData end ...
module RemoteProc module Server class Base def load_commands Dir[File.join(@options[:commands_dir], '*.rb')].each do |file| begin require file rescue LoadError => e logger.error "Can not require #{file}, you may want to check it. \n#{e.backtrace}" ...
require 'pp' require 'rubygems' require 'toystore' require 'adapter/cassandra' require 'cassandra/0.7' # You'll need Cassandra 0.7 to run this example. Run the following in # cassandra-cli to get everything in place: # # create keyspace Toystore; # use Toystore; # create column family Boom; class Message include T...
require_relative "../config/environment.rb" require 'active_support/inflector' require "pry" class InteractiveRecord def initialize(attr_hash = {}) attr_hash.each do |key, value| self.send(("#{key}="), value) end end def self.table_name self.to_s.downcase.pluralize end def self.column_na...
class ApplicationController < ActionController::API include ActionController::HttpAuthentication::Token::ControllerMethods # include ActionController::HttpAuthentication::Basic::ControllerMethods before_action :verify_authentication # before_action :authenticate # def authenticate # authenticate_or_requ...
class RemoveTaggedFromMovies < ActiveRecord::Migration def change remove_column :movies, :tagged, :boolean end end
class Circle attr_reader :columns, :rows def initialize radius @columns = @rows = radius * 2 lower_half = (0...radius).map do |y| x = Math.sqrt(radius**2 - y**2).round right_half = "#{155.chr * x}#{"#{0.chr}" * (radius - x)}" "#{right_half.reverse}#{right_half}" end.join @blob =...
class AddSocialUrlsToTools < ActiveRecord::Migration def change add_column :tools, :facebook_url, :string add_column :tools, :twitter_url, :string end end
class ProfilesController < ApplicationController before_filter :authorize_admin!, except: [:index, :show] before_filter :authenticate_user!, only: [:index, :show] before_action :set_profile, only: [:show, :edit, :update, :destroy] # GET /profiles # GET /profiles.json def index @profiles = Profile.all ...
ActiveExport.configure do |config| config.sources = { default: Rails.root.join('config', 'active_export.yml') } end
module Signup class Trigger < ApplicationService attr_accessor :siret_lookup_mock, :auth0_user_id_mock def initialize(params) @email = params[:email] @phone_number = params[:phone_number] @first_name = params[:first_name] @last_name = params[:last_name], @siret = params[:sir...
require './config/environment' class ApplicationController < Sinatra::Base configure do set :public_folder, 'public' set :views, 'app/views' enable :sessions set :session_secret, 'session secret' end get "/" do erb :welcome end helpers do def logged_in? !!session[:gamer_id]...
module ApplicationHelper def title(*parts) unless parts.empty? content_for :title do (parts << "Tracker").join(" - ") end end end def admins_only(&block) block.call if current_user.try(:admin?) end def authorized?(permission, thing, &block) block.call if can?(permission.t...
require "aethyr/core/actions/commands/acreate" require "aethyr/core/registry" require "aethyr/core/input_handlers/admin/admin_handler" module Aethyr module Core module Commands module Acprop class AcpropHandler < Aethyr::Extend::AdminHandler def self.create_help_entries help_...
desc "Copy emoji to the Rails `public/images/emoji` directory" task :emoji do require 'emoji' target = "#{Rake.original_dir}/public/images" `mkdir -p #{target} && cp -Rp #{Emoji.images_path}/emoji #{target}` end
class CreateTracks < ActiveRecord::Migration def change create_table :tracks do |t| t.string :title t.string :author t.string :instrument t.string :lyrics t.integer :song_id t.timestamps end end end
# frozen_string_literal: true require_relative 'rpn_calculator' # Client for the RPN calculator. Solicits input from the user, formats the input # into a valid expression sends input to be calculated and then handles the # response. class RPNClient include RPNCalculator # If no input source and output destin...
# # plytool.rb <anil20787@gmail.com> # Version 2013a # Sketchup::require 'sketchup' Sketchup::require 'extensions' ext = SketchupExtension.new("Plywood Tool", "plytool/plytool_main.rb") ext.description = "Draw ply in various sizes." ext.creator = "Anil Bhandary <anil20787@gmail.com>" Sketchup.register_extension(ext,...
require 'sinatra/base' require 'sinatra/flash' require 'uri' require 'bcrypt' require './database_connection_setup' require './lib/bookmark' require './lib/comment' require './lib/user' class BookmarkManager < Sinatra::Base enable :sessions, :method_override register Sinatra::Flash get '/' do erb :'users/n...
class Admin::VolunteerContactsController < Admin::ApplicationController load_and_authorize_resource respond_to :html, :xml, :json, :xls # GET /volunteer_contacts # GET /volunteer_contacts.xml def index @search = VolunteerContact.organization(current_user).search(params[:q]) @volunteer_contacts =...
class ChangeMoviesBoxofficeToString < ActiveRecord::Migration[5.2] def change change_column :movies, :box_office, :string end end
require "faraday" require "faraday_middleware" require "multi_json" require "addressable/template" module CodeUnion # More friendly RESTful interactions via Faraday and Addressable class HTTPClient def initialize(api_host) @api_host = api_host end def get(endpoint, params = {}) connection....
class FakeSms Message = Struct.new(:to, :body, :messaging_service_sid) HttpClient = Struct.new(:adapter, :last_request) LastRequest = Struct.new(:url, :params, :headers, :method) cattr_accessor :messages self.messages = [] def initialize(_username, _password, _account_sid, _region, _http_client); end d...
class Arrays # Обьявляем класс Мейн def initialize(first, second) # Обьявляем метод(тот же конструктор. Инициализатор вызывается по дефолту и принимает в себя 2 параметра) p "первое #{first} второе #{second}" # Выводим в терминал текст с ранее обьявленными параметрами array_fi...
class NodesController < ApplicationController before_action :authenticate_user!, except: [:index, :show, :rate] before_action :set_node, only: [:show, :edit, :update, :destroy] # GET /nodes # GET /nodes.json def index @story = Story.find(params[:story_id]) @nodes = @story.nodes end # ...
class Expr class Visitor def visit_assign_expr(expr);end def visit_binary_expr(expr);end def visit_call_expr(expr);end def visit_function_expr(expr);end def visit_get_expr(expr);end def visit_grouping_expr(expr);end def visit_literal_expr(expr);end def visit_logical_expr(expr);end ...
# -*- mode: ruby -*- # vi: set ft=ruby : # if there are any problems with these required gems, vagrant # apparently has its own ruby environment (which makes sense). To # install these gems (iniparse, for example), you need to run # something like: # # [unix]$ vagrant package install iniparse Vagrant.config...
class Message < ApplicationRecord belongs_to :user belongs_to :group mount_uploader :image, ImageUploader validates_presence_of :content, :user_id, :group_id end
require 'formula' class Rpg < Formula homepage 'https://github.com/rtomayko/rpg' url 'https://github.com/downloads/rtomayko/rpg/rpg-0.3.0.tar.gz' sha1 'acad232da1a560bdc0788bcfa203afcc58f0d7dc' head 'https://github.com/rtomayko/rpg.git' def install system "./configure", "--prefix=#{prefix}" system ...
require 'rails_helper' RSpec.describe Product, type: :model do let(:product) {build(:product)} it "should validate presence of name" do product.name= '' expect(product).to be_invalid end it "should validate presence of price" do product.price= '' expect(product).to be_invalid end it "should ha...
json.array!(@steps_takens) do |steps_taken| json.extract! steps_taken, :id, :steps_taken, :date_walked json.url steps_taken_url(steps_taken, format: :json) end
class CreateUserprofiles < ActiveRecord::Migration def change create_table :userprofiles do |t| t.string :callsign t.string :fname t.string :lname t.text :add1 t.string :state t.string :zip t.string :class_user t.date :efdate t.date :expdate t.references...
class AddDefaultValueToUnit < ActiveRecord::Migration def change change_column :products, :unit, :integer, default: 0 end end
class Product < ActiveRecord::Base belongs_to :category # has_and_belongs_to_many :orders has_many :reviews # order_products association has_many :order_products has_many :orders, through: :order_products # product must have a name validates :name, presence: true # product must mave a price, that p...
FactoryGirl.define do factory :promotion, :class => PromotionDimension do promotion_name "Christmas Sale 2006" price_reduction_type "50% Off" promotion_media_type "Banner" ad_type "None" display_type "Banner" coupon_type "None" ad_media_name "None" display_provider "Internal" promo...
class ShopsController < ApplicationController protect_from_forgery except: [:create] def index @shops = Shop. select("shops.*, count(quotations.id) as fallback_count"). joins("LEFT JOIN shops marketplaces ON (marketplaces.id = shops.marketplace_id)"). joins("LEFT JOIN quotations ON (quotation...
shared_examples_for 'search_with' do |operation_class, options={}| name = options.fetch(:name) context name do subject(:with_operator) do base_class.search_with_operator_by_name[name] end it { should be_a operation_class } options.each do |key, value| # skip :name since it use used to...
volume_dirs('storm.data') do type :persistent selects :single path 'nimbus' end node.set[:storm][:nimbus] = discover(:storm, :master) node.set[:storm][:zookeepers] = discover_all(:zookeeper, :server) template File.join(node[:storm][:conf_dir], 'storm.yaml') do owner node[:storm][:user] g...
name 'td-agent-files' version '16' # git ref dependency 'td-agent' # This software setup td-agent related files, e.g. etc files. # Separating file into td-agent.rb and td-agent-files.rb is for speed up package building build do pkg_type = project.packagers_for_system.first.id.to_s install_path = project.install...
class User < ActiveRecord::Base has_many :photos, dependent: :destroy has_many :tags has_many :tagged_photos, class_name: "Photo", foreign_key: "photo_id", through: :tags validates :username, presence: true validates_uniqueness_of :username validates_length_of :password, minimum: 8 has_secure_password ...
RSpec.describe 'as a user' do describe 'when I visit the book index page' do describe 'for each book' do before(:each) do @author = Author.create(name: "Sal") @author2 = Author.create(name: "Ian") @book1 = Book.create(title: "D...
class EditTickets < ActiveRecord::Migration[5.0] def change remove_column :tickets, :message create_table :ticket_messages do |tm| tm.text :message tm.references :ticket, foreign_key: true tm.boolean :new tm.timestamps end end end