text
stringlengths
10
2.61M
#Branching #when this condition of true is met, it skips all and goes to end if true puts "hello" else puts "bye" end #because this is false, it will go to the else and print bye if !true puts "hello" else puts "bye" end #---------------------------------------- #Evaluate 2 conditions with and && : condit...
class ProductsController < ApplicationController def create @category= Category.find(params[:category_id]) @product = Product.new(product_params) if @product.save redirect_to category_path(@category) end private def product_params params.require(:product).permit(:price, :name, :ca...
# Create a person class with at least 2 attributes and 2 behaviors. # Call all person methods below the class and print results # to the terminal that show the methods in action. class Person attr_accessor :first_name, :years_of_age def initialize(first_name, years_of_age) @first_name = first_name @years_...
MomentumCms.configure do |config| # The locale for the CMS # config.locale # Sets the default path for site fixtures # config.site_fixtures_path # Enables site fixtures # config.site_fixtures_enabled # config.admin_authentication # The style of the admin panel # Options here are: # nil - No adm...
class Recap < ApplicationRecord #belongs_to :event validates :attendance, :description, :event_id, presence: true validates :is_reviewed, inclusion: { in: [ true, false ] } validates :attendance, numericality: true end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{prep} s.version = "0.4.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_...
require 'rails_helper' RSpec.describe "/shortens", type: :request do let(:shorten) { create(:shorten, full_url: 'http://google.com') } let(:invalid_slug) { shorten.slug='NotValidSlug' shorten } let(:valid_attributes) { attributes_for(:shorten) } let(:invalid_attributes) { bad_attri...
class FontQuattrocentoSans < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/quattrocentosans" desc "Quattrocento Sans" homepage "https://fonts.google.com/specimen/Quattrocento+Sans" def install (share/"fonts").install "QuattrocentoSan...
class CreateSpells < ActiveRecord::Migration def change create_table :spells do |t| t.string :name t.integer :level t.boolean :ritual t.string :school t.text :components t.string :source t.text :description t.datetime :created_at t.date...
# use either select or reject # to return a new array identical in strucuture to the original # but only containing the integers that are multiples of 3 arr = [[2], [3, 5, 7], [9], [11, 13, 15]] a = arr.map do |sub| sub.select do |value| value % 3 == 0 end end p a
# -*- coding: utf-8 -*- module Plugin::YYBBS class User < Diva::Model include Diva::Model::UserMixin register :yybbs_user, name: 'YY-BBSユーザ' field.has :server, Plugin::YYBBS::Server, required: true field.string :username, required: true field.string :icon_path, required: true field.int :pos...
class FavoriteVideo < ActiveRecord::Base belongs_to :xvideo belongs_to :user validates_presence_of :xvideo validates_presence_of :user def as_json(options) super(include: [:xvideo, :user]) end end
class SessionsController < ApplicationController def new; end def create user = User.find_by email: (params_session :email) if user && user.authenticate(params_session(:password)) check_active_user user else flash[:danger] = t "controllers.session.m_unsuccess" render :new end en...
class ModifyColumnProvinciaProvNascToParticipant < ActiveRecord::Migration def self.up remove_column :participants, :prov_nasc remove_column :participants, :provincia end def self.down add_column :participants, :prov_nasc add_column :participants, :provincia end end
Rails.application.routes.draw do get 'bugs/search', to: 'bugs#index' get 'bugs/count', to: 'bugs#count' get 'bugs/:number', to: 'bugs#show' resources :bugs # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
module ApplicationHelper def validation_status(student, attr) return :ignore unless student.attributes[attr.to_s].present? student.errors[attr].present? ? :invalid : :valid end def validation_message(student, attr) case validation_status(student, attr) when :invalid ...
class User < ActiveRecord::Base validates :user_name, :password_digest, presence: true validates :user_name, uniqueness: true after_save :ensure_session_token has_many :cats, dependent: :destroy has_many :rental_requests, class_name: "CatRentalRequest", foreign_key: :user_id, ...
module Gameboy # http://gbdev.gg8.se/wiki/articles/The_Cartridge_Header class Rom def initialize(data) @data = data end def bytes @bytes ||= @data.unpack("C*") end def valid_header_checksum? x = 0 bytes[0x134..0x14c].each { |y| x = x + y + 1 } x = ~x + 1 # conver...
# frozen_string_literal: true require 'hanami/application/routes' module Sandbox class Routes < Hanami::Application::Routes define do slice :main, at: '/' do root to: 'home.show' get '/articles', to: 'articles.published' get '/articles/drafts', to: 'articles.drafts' end ...
class Homepage < ActiveRecord::Base self.table_name = "layout_homepage" outpost_model has_secretary include Concern::Scopes::PublishedScope include Concern::Associations::ContentAlarmAssociation include Concern::Callbacks::SetPublishedAtCallback include Concern::Callbacks::RedisPublishCallback include ...
# frozen_string_literal: true class SessionsController < ApplicationController # ensures the authorized function in the applicationController # does not run when trying to create an account or sign in skip_before_action :authorized, only: %i[new create welcome] # creates a new session then sets the current us...
class Team < ActiveRecord::Base has_many :members, class_name: 'Person', dependent: :restrict_with_error belongs_to :teamlead, class_name: 'Person' belongs_to :technicallead, class_name: 'Person' validates :name, presence: true validates :teamlead, presence: true validates :technicallead, prese...
module Rails module Generators class StrategyGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) desc <<DESC Description: Stubs out a strategy class in app/strategies directory. Examples: `rails g strategy login` This creates: app/strategies...
class Api::PinController < ApplicationController before_action :login_required_api params_required [:link, :title], only: :add params_required :link, only: :remove skip_before_action :verify_authenticity_token module ErrorCode NOT_FOUND = 2 end def all render json: current_member.pins end d...
module Boilerpipe::Extractors class ArticleExtractor def self.text(contents) doc = ::Boilerpipe::SAX::BoilerpipeHTMLParser.parse(contents) ::Boilerpipe::Extractors::ArticleExtractor.process(doc) doc.content end def self.process(doc) title = doc.title filters = ::Boilerpipe:...
class ChartsController < ApplicationController before_filter :verify_admin, except: [:recent_listens_for_user] def recent_listens_for_user render json: User.group(:email).order(sign_in_count: :desc).limit(10).sum(:sign_in_count) end def active_users render json: User.group(:email).order(sign_in_count: :de...
require 'rubygems' require 'test/unit' require File.dirname(__FILE__) + "/../lib/mailbox" class DataProcessor include Mailbox mailslot def process(data) p "#{data} was processed by Thread# #{Thread.current.object_id}" end end class ParallelEachExample < Test::Unit::TestCase def test_a_simple_paralle...
class AggregationsCollection < Hash def self.build_from_results(results) new.tap do |aggregations| results.aggregations.each do |key, aggregation| buckets = aggregation.buckets.map do |bucket| Aggregation.build_from_bucket(bucket, key) end buckets.sort_by!(&:name) a...
# frozen_string_literal: true # Include the customer interaction library. require 'customer' # # Class responsible for for invitation generation from # given input file, based on distance and location params. # class Inviter # # Takes the customer file and prepares an export # of customers we should invit...
require 'spec_helper' describe ResourceSearch do context "Associations" do it { should belong_to :search } it { should belong_to :resource } end end
# frozen_string_literal: true name 'rabbitmq' maintainer 'Chef, Inc. and contributors' maintainer_email 'mklishin@pivotal.io' license 'Apache-2.0' description 'Installs and configures RabbitMQ server' version '6.0.0' recipe 'rabbitmq', 'Install and configure RabbitMQ' recipe 'rabbitmq::systemd_limits', 'Sets up kerne...
class RecurringEventsController < ApplicationController before_action :set_recurring_event, only: [:show, :edit, :update, :destroy] def index @recurring_events = RecurringEvent.all end def show end def new @recurring_event = RecurringEvent.new end def edit end def create @recurring_...
# -*- encoding : utf-8 -*- FactoryGirl.define do factory :field_schema do |f| church applies_to 'person' end factory :field, class: Hash do |f| sequence(:name) { |n| "field#{n}" } sequence(:id) { |n| "#{n}" } type 'string' required false initialize_with { attributes } end end
class Vocabulary < ApplicationRecord def self.with_params(params) limit = params[:limit].to_i groups = [] chosen = [] if params[:priority] == 'all' groups << { limit: limit } elsif params[:priority] == 'unprioritized' groups << { priority: nil, limit: limit } elsif params[:prio...
FactoryGirl.define do factory :interest do trait :child do name "Child" end trait :refugee do name "Refugee" end end end
class AddPersonRefToUsers < ActiveRecord::Migration def change add_reference :users, :person, index: true reversible do |dir| dir.up do 'ALTER TABLE users ADD FOREIGN KEY (person_id) REFERENCES people(id)' end end end end
json.district do json.id @district.id json.name @district.name end
class ComponentsController < ApplicationController include ActionController::Live protect_from_forgery only: :index respond_to :json, only: [:repaired] def index @components = Component.all @transitions = ComponentStatusTransition.order('created_at DESC').first(20) end def repaired update(pa...
require 'rails' require 'active_model/railtie' # Comment taken from active_record/railtie.rb # # For now, action_controller must always be present with # rails, so let's make sure that it gets required before # here. This is needed for correctly setting up the middleware. # In the future, this might become an optional...
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. # IP Addresses used for internal network $so_ip ...
require 'test_helper' class GlobodnsClientTest < Test::Unit::TestCase def test_that_it_has_a_version_number refute_nil ::GlobodnsClient::VERSION end def test_initialize_without_settings assert_raise(ArgumentError) do klass.new(settings.delete_if { |k,v| k == :auth_token || k == :host }) end ...
class Module def const_missing(const_name) case const_name when :Task Rake.application.const_warning(const_name) Rake::Task when :FileTask Rake.application.const_warning(const_name) Rake::FileTask when :FileCreationTask Rake.application.const_warning(const_name) Rak...
class InvoiceDetail < ApplicationRecord belongs_to :customer has_many :invoices enum identification_type: %i[consumidor_final cedula ruc] end
module GraphQLServer::Instrumentation module Field def instrument_resolve return resolve unless GraphQLServer.config.instrument_fields @start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) result = resolve if result.is_a?(Promise) result.then do |value| end_tim...
require File.dirname(__FILE__) + '/setup' require 'javaclass/dsl/java_name_factory' module TestJavaClass module TestDsl class TestJavaNameFactory < Test::Unit::TestCase include JavaClass::Dsl::JavaNameFactory def test_java_class assert_equal('java.lang.String', java.lang.String) end ...
#该表建立百度的tag名字和我们系统的tag名字的对应表 #问题,为何要建立自己的标签系统?唯一的担心就是百度的标签可读性不好,或者我们需要一个可读的标签名字 #实际中,标签的编号可能会有一定的规律, 如物业企业的标签可能普遍带有wuye_qiye_*, wuye_custermer_* class CreateTags < ActiveRecord::Migration def self.up create_table :tags do |t| t.string :p_tag #百度的tag t.string :sv_tag#服务的tag t.string :apikey #百度的...
require 'map' RSpec.describe Array do describe '#customMap' do it "behaves same way as Array.map" do array = (0..9).to_a.shuffle expect(array.customMap{|elem| elem*2}).to eq(array.map{|elem| elem*2}) end end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html concern :paginatable do get '(page/:page)', action: :index, on: :collection, as: '' end resources :projects, only: [:index] do resources :devices, only: [:index] do ...
class AddColumn < ActiveRecord::Migration[5.0] def change change_table :questions do |t| t.integer :user_id end end end
class CreatePurchases < ActiveRecord::Migration def change create_table :purchases do |t| t.integer :project_id t.integer :purchasing_user_id t.integer :selling_user_id t.decimal :amount, scale: 2, precision: 8 t.timestamps end end end
class SessionsController < ApplicationController def new @user = User.new render :new end def create # @user = User.new(session_params) user = User.find_by_credentials( session_params[:username], session_params[:password] ) if user login_user! user ...
module PermissionHelper def user_has_permision_to_change?(model) current_user && (current_user == model.user || current_user.admin?) end end
class DeleteStatusFromTransaction < ActiveRecord::Migration def change remove_column :transactions, :status end end
# encoding: utf-8 require 'watir-webdriver' require 'json' require 'pathname' require "open-uri" def login(browser) browser.goto "http://www.medialoot.com/" browser.span(:id => "login_headline").click browser.text_field(:name => "username").set( ENV['MEDIALOOT_LOGIN']) browser.text_field(:name => "password"...
# frozen_string_literal: true module Zendesk class Snitcher class Pattern class Default < Zendesk::Snitcher::Pattern def go Zendesk::Ticket::STATUSES.keys.each do |status| p "Tickets update. Time: #{Time.now}. Status: #{status}" to_status = status.to_s == "new" ? "...
class GDG::Maceio::Barcode < GDG::Barcode def name "Barcode Maceio #{date}" end end
require 'rubygems' # poor people still on 1.8 require 'bundler/setup' Bundler.require gem 'redis', '>= 3.0.0' require 'redis' $LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../lib') # Start our own redis-server to avoid corrupting any others REDIS_BIN = 'redis-server' REDIS_PORT = ENV['REDIS_PORT']...
module Vagrant module Butcher module Action class CopyGuestKey include ::Vagrant::Butcher::Helpers::Action include ::Vagrant::Butcher::Helpers::KeyFiles def initialize(app, env) @app = app end def call(env) begin @app.call(env) ...
module HBase module Operation module RowOperation Converter = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', "'" => '&apos;', '"' => '&quot;' } def row_timestamps(table_name, name) raise NotImplementedError, "Currently not supported in native hba...
require_relative 'grid' class Block def initialize(block_array, rows, columns) @block_array = block_array @rows = rows @columns = columns end def block_array_count @block_array.count * @block_array[0].count end def empty? @block_array = true end def f...
Qiankun::Admin.controllers :room_cars do get :index do @title = "Room_cars" @room_cars = RoomCar.all render 'room_cars/index' end get :new do @title = pat(:new_title, :model => 'room_car') @room_car = RoomCar.new render 'room_cars/new' end post :create do @room_car = RoomCar.new(...
class LibraryCatFind < ActiveRecord::Base # Use view instead of table library_cats self.table_name = 'library_vcats' self.primary_key = 'id' # Scopes # Relations belongs_to :library # Validations validates_length_of :lib_code, minimum: 3, maximum: 255 end
require 'rails_helper' RSpec.describe "yh_pictures/edit", type: :view do before(:each) do @yh_picture = assign(:yh_picture, YhPicture.create!( :action => "MyString", :service_type => "MyString", :content_id => "MyString", :urgency => "MyString", :category => "MyString", :class...
class AddTextAlignToBlocks < ActiveRecord::Migration[5.0] def change add_column :blocks, :text_align, :string end end
require 'csv' module Dashboard class EntriesController < Dashboard::BaseController before_filter :require_current_challenge, only: :index load_and_authorize_resource def index add_crumb 'Propuestas' @challenges = organization_challenges @current_challenge = current_challenge @entr...
require 'cloudformation_mapper/resource' class CloudformationMapper::Resource::AwsPropertiesSnsPolicy < CloudformationMapper::Resource register_type 'AWS::SNS::TopicPolicy' type 'Template' parameter do type 'Template' name :Properties parameter do type 'JSON object' name :PolicyDocum...
# encoding: utf-8 #! /usr/bin/env ruby ## # Auteur CrakeTeam # Version 0.1 : Date : Mon Mar 17 09:42 2013 # require_relative 'Fenetre' class FenetreAccueil < Fenetre @imageBanniere @boutonPartieRapide @boutonJouer @boutonProfil @boutonEditeur @boutonOptions @boutonCredits @boutonQuitter @boutonDe...
json.array!(@shops) do |shop| json.extract! shop, :id, :name, :tel, :time_weekdays, :time_sat, :time_sun, :time_holidays json.url shop_url(shop, format: :json) end
module Readers class AboutController < ReadersController before_action :set_about def show @list_texts = AboutListText.where(about_id: @about.id) end private # Use callbacks to share common setup or constraints between actions. def set_about @about = About.first end e...
class AddPositionToApplicationLanguages < ActiveRecord::Migration def change add_column :tr8n_application_languages, :position, :integer end end
class FixDuplicateDelegateIds < ActiveRecord::Migration def up Delegate.transaction do ids_to_delete = [] # get duplicate delegate records puts 'getting duplicate delegate records' sql = "select conference_id, all_delegate_id from (select conference_id, all_delegate_id, count(*) as c " ...
require "formula" class Ipmcctools < Formula homepage "https://github.com/ipmcc/tools" head "https://github.com/ipmcc/tools", :using => :git sha1 "" def install Dir.open(Dir.pwd).each do |filename| next if not File.executable? filename next if File.directory? filename bin.install filen...
module UserAuthentication # For authentication STATUSES = [['Administrator', :admin],['Leader', :leader],['Coach', :coach]].freeze def role?(authorized_role) return false if status.nil? status.downcase.to_sym == authorized_role end # login by username def User.authenticate(username, password) ...
# frozen_string_literal: true module SeeYouCup FileNotFound = Class.new(StandardError) end
class PointsController < ApplicationController def index @points = Point.all end end
# This assumes that the given array is sorted and uses linear search to locate a particular value. module Kata module Algorithms module Searching class LinearSearchOnOrderedArray < Struct.new(:ordered_array, :value_to_search_for) def search return nil if ordered_array.nil? || value_to_sear...
# Max sum of non-negative numbers. In case of tie, return array with max len class Solution # param a : array of integers # return a array of integers def maxset(a) return [] if a.nil? || a.size == 0 sum_so_far = max_sum = 0 len = max_len = 0 start_index = max_start_index = 0...
class Letter < ActiveRecord::Base validates :user_id, presence: true validates :sender_id, presence: true default_scope -> {order('created_at DESC')} after_initialize :defaults belongs_to :sender belongs_to :user def defaults self.category ||= 'sale' end end
require 'hanami/utils/class_attribute' require 'hanami/utils/callbacks' module Hanami module Action # Before and after callbacks # # @since 0.1.0 # @see Hanami::Action::ClassMethods#before # @see Hanami::Action::ClassMethods#after module Callbacks # Override Ruby's hook for modules. ...
class CreateHistorics < ActiveRecord::Migration[5.2] def change create_table :historics do |t| t.references :users, foreign_key: true t.references :exchanges, foreign_key: true t.references :currencies, foreign_key: true t.date :date t.decimal :value t.timestamps end end...
#!/usr/bin/env ruby $: << File.expand_path(File.dirname(__FILE__) + '/../lib') require "stringio" module Glyph; end begin unless Glyph.const_defined? :MODE then Glyph::MODE = {:debug => false, :lite => false, :test => true} end rescue end require "glyph" require "glyph/commands" Glyph['system.quiet'] = true ...
## search_users_steps.rb # Allows the users to be searched # # @author Helen Harman # @created November 2014 require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "search_helper")) When /^I type "([^\"]*)" into the search field "([^\"]*)" and I choose "([^\"]*)"$/ do |data, search_field, select_...
require_relative 'test_helper' class MultilineCommandParsingTests < SlightishTest suite('basic multiline', %[ $ echo "this is\\ a multiline command" ]).should do |s| assert_equal(1, s.test_cases.length) assert_case(s.test_cases[0], 'echo "this is a multiline command"', [1, 2]) end suite('mo...
class RestaurantsRegion < ActiveRecord::Base belongs_to :restaurant belongs_to :region end
Given /^the locale is "([^\"]*)"$/ do |locale| I18n.locale = locale.to_sym end
class StanzasController < ApplicationController before_filter :load_stanza, :only => [:show, :edit, :update, :destroy] before_filter :require_user, :only => [:new, :create, :edit, :update, :destroy] before_filter :convert_blank_params, :only => [:create, :update] before_filter :block_private, :only => [:show] ...
class Article < ActiveRecord::Base ARTICLE_FILE_TAG = 'article' RESUME_RUS_FILE_TAG = 'resume_rus' RESUME_ENG_FILE_TAG = 'resume_eng' COVER_NOTE_FILE_TAG = 'cover_note' REVIEW_FILE_TAG = 'review' STATUS_CREATED = 0 STATUS_TO_REVIEW = 1 STATUS_REVIEWED = 2 STATUS_REJECTED_BY_CENSOR = 3 STATUS_APPROVE...
require 'json' require 'youtube_it' class Youtube < ActiveRecord::Base def self.find_video_by_query(query,page=1) client = YouTubeIt::Client.new res = client.videos_by(:query => "#{query}", :page => "#{page}", :per_page => 15, :alt => 'json') video_info = Array.new res.videos.each do |video| v...
require 'set' require 'jane/version' module Jane class << self attr_accessor :boot_steps end def self.add_boot_step(callable = nil, &boot_step) @boot_steps ||= Set.new boot_steps.add(callable || boot_step) end def self.boot! if !boot_steps.nil? && !boot_steps.empty? boot_steps.each(&...
class FontSyneMono < Formula head "https://github.com/google/fonts/raw/main/ofl/synemono/SyneMono-Regular.ttf", verified: "github.com/google/fonts/" desc "Syne Mono" desc "Another take on letting go of control" homepage "https://fonts.google.com/specimen/Syne+Mono" def install (share/"fonts").install "Syn...
class VlanCounters < BinData::Record endian :big uint32 :vlan_id uint64 :octets uint32 :ucastPkts uint32 :multicastPkts uint32 :broadcastPkts uint32 :discards end
require "fpm/namespace" # Abstract class for a "thing to build a package from" class FPM::Source # standard package metadata %w( name version iteration architecture maintainer category url description ).each do |attr| attr = :"#{attr}" define_method(attr) { self[attr] } ...
class CreateMembers < ActiveRecord::Migration def change create_table :members do |t| t.string :first_name t.string :last_name t.string :email t.integer :location_id t.string :country_code t.string :phone_number t.integer :team_id t.string :shib t.boolean :cap...
require 'bcrypt' class User attr_reader :id, :email, :password def initialize(id:, email:, password:) @id = id @email = email @password = password end def self.add(email:, phone_num:, password:) encrypted_password = BCrypt::Password.create(password) users = [] result = DatabaseConnecti...
class RenameFieldsOfAttachment < ActiveRecord::Migration def change add_column :attachments, :payload_file_name, :string add_column :attachments, :payload_content_type, :string add_column :attachments, :payload_file_size, :integer add_column :attachments, :payload_updated_at, :datetime remove...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authorized helper_method :logged_in? def current_guard if session[:user_id] @guard = Guard.find_by(id: session[:user_id]) else end end def logged_in? !!current_guard end ...
class PostsController < ApplicationController before_filter :find_comment respond_to :html def index @posts = @comment.posts respond_with(@posts) end def create unless params[:parent_id].blank? @parent_post = Post.find(params[:parent_id]) @post = @parent_post.children.create!(params[...
require './lib/encryptor' require './lib/decryptor' class Enigma def initialize @encryptor = Encryptor.new @decryptor = Decryptor.new end def build_encrypt(message, key, date) encryption_hash = { encryption: @encryptor.encrypt_message(message, key, date), key: key, date: date }...
class AddLastActionToContacts < ActiveRecord::Migration[5.1] def change add_column :contacts, :last_action_type, :string add_column :contacts, :last_action_date, :datetime end end
class TodosController < ApplicationController before_action :set_list before_action :set_todo, except: [:create] def create @list = List.find(params[:list_id]) @todo = @list.todo.create(:content => params[:content]) redirect_to lists_path end def destroy if @todo.destroy flash[:success] = t('tod...