text
stringlengths
10
2.61M
class HomeController < ApplicationController def index if current_user @nation = current_user.nation @alliance = Nation.in_alliance(@nation.alliance) end end end
require './lib/node' class LinkedList attr_reader :head def initialize @head = nil end def append(data) if @head == nil @head = Node.new(data) else last_node.set_next(Node.new(data)) end end def count nodes = 0 current_node = @head if @head != nil nodes = 1 ...
namespace :custom do desc "создание учетной записи" task :help_login do User.create(email: "admin@admin.dev", password: "qwerty1234") end end
execute "disable-default-site" do command "a2dissite default" notifies :reload, resources(:service => "apache2"), :delayed only_if {File.exists?(File.join(node[:apache][:dir], "sites-enabled", "000-default")) || File.exists?(File.join(node[:apache][:dir], "sites-enabled", "default"))} end
# encoding: UTF-8 module CDI module V1 module ChatMessages class BatchMarkService < BaseActionService action_name :batch_chat_message_mark_read attr_reader :chat_message_reads def initialize(chat_room, user, options={}) @chat_room = chat_room @user = user ...
class Changeorigintostringnottext < ActiveRecord::Migration[6.1] def change change_column :bottles, :origin, :string end end
require 'littlewire' wire = LittleWire.connect pin = :pin4 num_leds = 19 MaxBPM = 500 AveragedTaps = 8 puts "Outputtting data to LittleWire pin named '#{pin}'" strobe_duration = 0.01 bpm = 30 last_tap = Time.now.to_f tap_bpms = [] last_strobe = Time.now.to_f reset = false wire.ws2811(pin).black! puts "Enter BPM and...
class CreateDepartments < ActiveRecord::Migration def change create_table :departments do |t| t.string :name t.string :description t.string :email_id t.string :phone_number t.string :fax t.timestamps end end end
# module FluxHue VERSION = "0.1.0" end
class Location < ActiveRecord::Base belongs_to :mission belongs_to :company belongs_to :candidate before_save :check_not_select_country def check_not_select_country self.country = "" if self.country == I18n.translate("select_country") end #TODO check if used ? def empty? self.address_one.bla...
require './lib/credit_check' require 'minitest/autorun' require 'minitest/pride' class CreditCheckTest < Minitest::Test def setup card_number = "4929735477250543" other_card_number = "5541801923795240" @credit_check = CreditCheck.new(card_number) @bad_credit_check = CreditCheck.new(other_card_numbe...
class AddNewsletterUpdatedToUsers < ActiveRecord::Migration def change add_column :users, :newsletter_updated, :boolean, default: true end end
class Group < ActiveRecord::Base before_validation :get_course before_validation :get_name belongs_to :direction has_many :lessons validates :direction_id, presence: true validates :year_of_enter, presence: true validates :name, presence: true validates :course, presence: true def get_course se...
class ArticlesController < ApplicationController http_basic_authenticate_with name: "aaa", password: "aaaa", only: :destroy #스캐폴딩 컨트롤러 클래스 def index @articles = Article.all #@템플릿 변수 로직과 디자인을 결합 erb 와 rb #템플릿에 넣고 싶은 데이터를 준비한다 end def show @article = Article.find(params[...
require 'minitest/pride' require 'minitest/autorun' require 'pry' require './lib/round.rb' class RoundTest < Minitest::Test def test_existence card_1 = Card.new("3","Hearts") card_2 = Card.new("4", "Clubs") card_deck = Deck.new([card_1, card_2]) round = Round.new(card_deck) assert_instance_of R...
require 'test_helper' class Pullrequest::CommentDeletedTest < ActiveSupport::TestCase def setup @params = { channel: '@slackbot', actor: FactoryGirl.attributes_for(:user), pullrequest: FactoryGirl.attributes_for(:pullrequest), repository: FactoryGirl.attributes_for(:repository), com...
#Attr Methods # I worked on this challenge [by myself] # I spent [1] hours on this challenge. class NameData attr_reader :name def initialize @name = "Chris" end end class Greetings def initialize @name = NameData.new end def hello puts "Hello #{@name.name}! How wonderful to see you today!...
module V1 class EventsController < ApplicationController before_action :set_event, only: [:show, :update, :destroy] before_action :set_itinerary def index @events = @itinerary.events.all json_response(@events) end def show json_response(@event) end def create @ev...
class CategoryPosition < ActiveRecord::Base belongs_to :category validates :category_id, uniqueness: true validates :position, uniqueness: {scope: [:category_id]} acts_as_list end
# device_group.rb # === Authors # # Sam Dacanay <sam.dacanay@logicmonitor.com> # Ethan Culler-Mayeno <ethan.culler-mayeno@logicmonitor.com> # # Copyright 2016 LogicMonitor, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
require 'devise_zxcvbn/email_tokeniser' module Devise module Models module Zxcvbnable extend ActiveSupport::Concern delegate :min_password_score, to: "self.class" included do validate :not_weak_password, if: :password_required? end private def not_weak_password ...
# -*- mode: ruby -*- # vim: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "ec2" config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dum...
class ServiceMap < ApplicationRecord belongs_to :station belongs_to :service belongs_to :room end
# == Schema Information # # Table name: users # # id :integer not null, primary key # active :boolean default(TRUE), not null # email :string default(""), not null # encrypted_password :string default(""), not null # nam...
module BadgeConcerns module LearningTrackBadgeable extend ActiveSupport::Concern include BadgeConcerns::SimpleBadgeable included do after_update :award_on_track_created end private def award_on_track_created if self.changed.include?("status") && self.status_published? if ...
#!/usr/bin/env ruby module MyAwesomeModule def awesome_method puts "Module = MyAwesomeModule, Method = awesome_method" end end class MyAwesomeClass include MyAwesomeModule end obj = MyAwesomeClass.new obj.awesome_method
class UsersController < ApplicationController before_action :authenticate_user! expose(:user) expose(:reviews) { current_user.reviews.last(5) } def show end def edit current_user.update!(user_params) redirect_to user_profile_path end private ...
require 'test_helper' class EventsControllerTest < ActionController::TestCase def setup @event = events(:test) end test "should redirect to main page when not logged in" do assert_no_difference 'Event.count' do post :create, event: { event_name: "TEST" } end assert_redirected_to login_url...
require_relative 'planet' require_relative 'solar_system' def main solar_system = SolarSystem.new("Sun") mercury = Planet.new("Mercury", "light-grey", 3.285e23, 5.800e7, "if you lived on Mercury you'd have a birthday every 3 months.") venus = Planet.new("Venus", "white", 4.867e24, 1.080e8, "it is named after the...
require 'rails_helper' RSpec.describe "home routing" do it "routes home" do expect(get: "/").to route_to(controller: "home", action: "index") end end
class Partner class RatingReportSerializer < ActiveModel::Serializer attributes RatingReport.base_columns end end
require 'nokogiri' module Source class Play def initialize(path) @path = path end def load(output = true) @doc = Nokogiri::XML load_file(output) do |config| end puts "Feed source has #{@doc.css('Act').size} acts, #{@doc.css('Scene').size} scenes, #{@doc.css('Paragraphs').size} p...
require 'active_support' require 'active_support/core_ext/string' class Converter attr_accessor :source_unit, :target_unit attr_reader :unit_map # These maps provide lambdas that convert to and from the base unit # First lambda is how to convert *to* the base unit # Second lambda is the inverse, converting ...
class FavoritesController < ApplicationController def index @user = User.find(params[:user_id]) @movies = @user.favorites respond_to do |format| format.html # index.html.erb format.xml { render :xml => @favorites } end end # DELETE /favorite_movies/1 # DELETE /favorite_movies/1....
class AddCommentCountAndMyListCountToMovie < ActiveRecord::Migration def change add_column :movies, :comment_counter, :integer add_column :movies, :mylist_counter, :integer end end
Puppet::Type.newtype(:razor_policy) do ensurable newparam(:name, :namevar => true) do desc "The name of the policy; used internally by Razor to identify the policy" end newproperty(:repo) do desc "The name of the repo this policy should use." munge do |value| if value.is_a?(String) {...
# 这是一种运行 ruby-prof 的方式 在源码中插入 ruby-prof 的启动和停止代码 # 第二种是 使用 命令 ruby-prof -p xxx filename.rb # ruby-prof -p graph_html rprofile_test.rb -f dot.html 这句命令将产生 dot.html 文件,分析内容都在里面。 同样的可以保存为 txt dot 等文件格式 # # xxx: #flat - Prints a flat profile as text (default). #flat_with_line_numbers - same as flat, wi...
# frozen_string_literal: true module GraphQL class Query # Read-only access to query variables, applying default values if needed. class Variables extend Forwardable # @return [Array<GraphQL::Query::VariableValidationError>] Any errors encountered when parsing the provided variables and literal ...
require File.dirname(__FILE__) + "/../../spec_helper" describe Instructors::AccessController do let(:current_user) { Factory.stub(:instructor) } let(:mock_membership) { mock_model(Membership) } let(:mock_scenario) { mock_model(Scenario, {:name => ""}) } before { controller.stub(:current_user).and_return(cur...
require 'rake' require 'rake/testtask' require 'rake/rdoctask' desc "Generates documentation" task :doc => :dist do require 'pdoc' PDoc.run({ :source_files => Dir.glob(File.join("src", "**", "*.js")), :destination => 'doc', :syntax_highlighter => :pygments, :markdown_parser => :maruku, :pret...
module OAuth class Facebook < Base TOKEN_ENDPOINT = 'https://graph.facebook.com/v8.0/oauth/access_token'.freeze PROFILE_ENDPOINT = 'https://graph.facebook.com/me'.freeze AUTHORIZATION_ENDPOINT = 'https://www.facebook.com/v8.0/dialog/oauth'.freeze class << self def authorization_ur...
class Post < ActiveRecord::Base has_and_belongs_to_many :tags belongs_to :user end
# frozen_string_literal: true class ThemesController < ApplicationController def index @themes = Theme.all end def show @theme = Theme.find(params[:id]) @student = current_user end def new @theme = Theme.new @courses = Course.all end def create @theme = Theme.new(theme_params) ...
class AddDateOfSubmissionToTeachers < ActiveRecord::Migration def change add_column :teachers, :date_of_submission, :date end end
require 'spec_helper' RSpec.describe CQM::Converter::HDSRecord do before(:all) do # Initialize a new HDS converter. @hds_record_converter = CQM::Converter::HDSRecord.new end it 'converts HDS to QDM and maintains id' do hds_eh_id_test = Record.new.from_json(File.read('spec/fixtures/hds/records/eh/id_...
require 'minitest/autorun' require 'minitest/pride' require './lib/ingredient' require './lib/recipe' class RecipeTest < Minitest::Test def setup @banana_bread = Recipe.new("Banana Bread") end def test_it_exists assert_instance_of Recipe, @banana_bread end def test_it_has_attributes assert_equ...
class RemoveAuthenticityTokenFromUsers < ActiveRecord::Migration[5.2] def change remove_column :users, :authenticity_token, :string end end
require_relative "errors" require 'mail' class UdaciList attr_reader :title, :items @@TYPES = ["todo", "event", "link"] @@EMAIL = { from: "udacilist@udacilist.com", port: 1025, subject: "Your Todo List", address: "localhost" } def initialize options={} @title = options[:title] ? optio...
require 'psd/layer_info' class PSD class ObjectEffects < LayerInfo def self.should_parse?(key) key == 'lfx2' end def parse version = @file.read_int descriptor_version = @file.read_int @data = Descriptor.new(@file).parse return self end end end
# This controller is used to manager user # History: June 06, 2013 # By NamTV class UsersController < ApplicationController before_filter :authenticate_user! SORT_MAP = { 1 => "full_name", 2 => "username" } ## #Get user list except an user with specify ID #Parameters:: # * (Integer) *iDisplayLeng...
module TopList module TopListHelper def toggle_top_position return unless self.respond_to? :top_list_item if self.top_list_item self.top_list_item.destroy else self.build_top_list_item(position: 0) end self.save end end end
class Resort < ActiveRecord::Base has_many :reports belongs_to :favorites def current_report self.reports.last end end
require 'spec_helper' describe ProjectsController do render_views describe "GET 'new'" do it "should be successful" do get :new response.should be_success end it "should have the right title" do get :new response.should have_selector("title", :content => "Create Project") ...
# == Schema Information # # Table name: episodes # # id :integer not null, primary key # serie_id :integer not null # title :string not null # synopsis :text not null # video_url :string not null # created_...
class CreateMessages < ActiveRecord::Migration def change create_table :messages do |t| t.string :encrypted_name t.string :encrypted_email t.string :encrypted_subject t.text :encrypted_message t.datetime :created_at, null: false end end end
require 'rails_helper' RSpec.describe Api::V1::Customers::PropertiesController, type: :controller do include Serializable let(:customer) { FactoryBot.create(:customer) } let(:neightborhood) { FactoryBot.create(:neightborhood) } let(:property) { FactoryBot.create(:property) } let(:customer2) { FactoryBot.cre...
class TicTacToe def initialize(board = nil) @board = Array.new(9, " ") end WIN_COMBINATIONS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]...
class FontGothicA1 < Formula head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/gothica1" desc "Gothic A1" homepage "https://fonts.google.com/specimen/Gothic+A1" def install (share/"fonts").install "GothicA1-Black.ttf" (share/"fonts").install...
# -*- coding: utf-8 -*- # Url 関係設定. module OpensocialWap module Config # # 実行時にURLを決定したいときの設定 # # かなり決め打ちだけど変更したかったらサブクラスを作ればいい # 引数を受け取ってそれを返すなら動的にした意味がないので普通の静的な方を使えばいい # class DynamicUrl def initialize(context) @context = context end def container_host ...
class Post < ApplicationRecord belongs_to :user belongs_to :category, optional: true has_many :images, dependent: :destroy has_many :comments accepts_nested_attributes_for :images, allow_destroy: true validates :images, :name, :category, :brand, :shop, :praice, :star, :remark, presence: true end
module JsonTableSchema module Types class Integer < Base def name 'integer' end def self.supported_constraints [ 'required', 'pattern', 'enum', 'minimum', 'maximum', ] end def type ::Integer en...
class OrderedFood < ApplicationRecord belongs_to :order belongs_to :food end
require File.expand_path(File.dirname(__FILE__) + '/../../simple_spec_helper') class TestAbility def initialize(*args) end end describe Lolita::Extensions::Authorization::Proxy do let(:klass){ Lolita::Extensions::Authorization::Proxy } let(:proxy){ klass.new(Object.new,{}) } around(:each) do |example| ...
class RemoveMemberIdFromProfiles < ActiveRecord::Migration[5.0] def change remove_column :profiles, :member_id, :integer, null: false end end
class Admin::DashboardController < ApplicationController def show @ProductsCount = Product.all.count @CategoriesCount = Category.all.count end end
class Visualization < ActiveRecord::Base # Executes the query to select students we are interested in # Returns an ActiveRecord::Relation def self.student_demographic_query(countries, genders, classes) result = Student.none filtered = GeneralStats.student_by_country_gender(countries, genders...
class EdgeTypesController < ApplicationController before_filter :authenticate_user! # GET /edge_types # GET /edge_types.json def index @edge_types = EdgeType.all respond_to do |format| format.html # index.html.erb format.json { render json: @edge_types } end end # GET /edge_ty...
require 'puppet_x/brocade/fact' require 'puppet_x/brocade/possible_facts' require 'puppet_x/brocade/sorter' require 'puppet_x/brocade/dsl' #Lookup class which helps in registering the facts and retrieving the fact values class PuppetX::Brocade::Facts include PuppetX::Brocade::Dsl attr_reader :transport def ini...
# frozen_string_literal: true class Client::LandingController < ApplicationController layout 'client' before_action :authenticate_client! def index respond_to do |format| format.html { render :index } format.json do render json: { data: 'Hello Client!' } end end end end
class UsersController < ApplicationController before_filter :authenticate_user! load_and_authorize_resource def index end def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:notice]...
class AddFundraiserGoalToFundraisers < ActiveRecord::Migration def change add_column :fundraisers, :fundraiser_goal, :integer end end
require 'rails_helper' describe 'songs', js: true do let( :song_name ) { 'Nirvana - In Bloom' } let!( :song ) { Song.create( author: 'Nirvana', title: 'In Bloom' ) } it 'lists songs' do visit '/' expect( page ).to have_content( song_name ) end end
#encoding: utf-8 namespace :exchange_rate do desc "初始化 货币中类表" task :init_exchange_rate => :environment do #['英文名称', '中文名称', '和人民币对应的汇率'] rates = [['CNY', '人民币',1]] rates.each do |r| ExchangeRate.where(:name_en => r[0]).first_or_create(:name_en => r[0], :name_zh => r[1], :rate => r[2]) end...
class PostsController < ApplicationController def index @posts = Post.visible_to( current_user ).where( "posts.created_at > ?", 7.days.ago ).paginate( page: params[ :page ], per_page: 10 ) end end
json.exercises do json.partial! 'api/v1/exercises/show', collection: @exercises, as: :exercise end
class SpreeShared::TenantInitializer attr_reader :db_name def initialize(db_name) @db_name = db_name ENV['AUTO_ACCEPT'] = 'true' ENV['SKIP_NAG'] = 'yes' end def create_database ActiveRecord::Base.establish_connection #make sure we're talkin' to db ActiveRecord::Base.connection.execute("DRO...
require 'rails_helper' RSpec.describe Task, type: :model do describe 'Taskバリデーションチェック' do it "titleが空ならバリデーションが通らない" do task = FactoryBot.build(:task, title:'', content: "content") expect(task.valid?).to eq(false) end it "contentが空ならバリデーションが通らない" do task2 = FactoryBot.build(:task, titl...
class Exporter::FieldContactNames < Exporter::Exporter def column_definitions column("fc_num") { record.fc_num } column("race") { record.race } column("age") { record.age } column("build") { record.build } column("hair_style") { record.hair_style } column("skin_tone") { record.skin_tone } ...
class TimeframesController < ApplicationController # GET /timeframes # GET /timeframes.json def index @timeframes = Timeframe.all @timeframes_json = @timeframes.map{ |e| {:timeframe => e}} respond_to do |format| format.html # index.html.erb format.json { render json: @timeframes_json} ...
module AnnualReports class RebuildOneJob < ApplicationJob def perform(annual_report_id) RebuildOneService.new(annual_report_id).call end end end
class Item < ApplicationRecord has_many :invoice_items, dependent: :destroy has_many :invoices, through: :invoice_items belongs_to :merchant validates :name, presence: true validates :description, presence: true validates :unit_price, presence: true validates :merchant_id, presence: true def self.sear...
module Datapathy::Model module Discovery extend ActiveSupport::Concern # A model (ServiceDescriptor) might have an actual attribute :service_type # so hide ours so we can still determine the service_descriptors content-type # when registering it def _service_type self.class.service_type ...
# frozen_string_literal: true require 'test_helper' module Vedeu describe YCoordinate do let(:described) { Vedeu::YCoordinate } let(:instance) { described.new(geometry) } let(:geometry) {} describe '#initialize' do it { instance.must_be_instance_of(described) } it { instance.instanc...
class ChangeBadgeRules < ActiveRecord::Migration[5.2] def change add_column :badge_rules, :badge_id, :integer end end
require 'helper_frank' module Rdomino describe Item do before do @doc, @doc2 = Rdomino.local[:scratch].fixtures [{:li => %w[z1 z2]}, {:hallo => 'welt'}] @li = @doc[:li] end it 'creates nonexistent item' do item = @doc.find_or_creat...
require_relative './yes_no_question' class CovidTasteQuestion < YesNoQuestion TEXT = 'Percibiste una marcada pérdida del gusto de manera repentina?'.freeze def initialize super(TEXT) end end
require 'rails_helper' RSpec.describe SessionsHelper, type: :helper do before(:each) do @user = User.create!( :name => "John", :email => "my@email.com", :password => "Password", :password_confirmation => "Password" ) end it "should set the current ...
class Question attr_reader :good_response def initialize(current_player) @current_player = current_player @question = generate_question @answer = gets.chomp.to_i @good_response = good_response? end def generate_question numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ...
# Problem 183: Maximum product of parts # http://projecteuler.net/problem=183 # Let N be a positive integer and let N be split into k equal parts, r = N/k, so that N = r + r + ... + r. # Let P be the product of these parts, P = r ×r × ... ×r = r^k. # # For example, if 11 is split into five equal parts, 11 = 2.2 + 2.2...
class Admin::CommentsController < Admin::ApplicationController def index @comments = Comment.all end def show end def edit @comment = Comment.find(params[:id]) end def update @comment = Comment.find(params[:id]) if @comment.update(comment_params) redirect_to edit_admin_end_user_path(@...
class CharityDescriptionToText < ActiveRecord::Migration def change change_column :charities, :description, :string, :limit => 2500 end end
class PropertyPresenter < ApplicationPresenter def initialize(property, game) @property = property @game = game end def as_json(*) { id: @property.id, name: @property.name, color: @property.color_set.color, category: create_category, price_data: price_data, owner_i...
require 'rails_helper' describe Contact do it { should validate_presence_of :firstname } it { should validate_presence_of :username } it { should validate_presence_of :phonenumber } end
require "rails_helper" RSpec.describe "articles", :type => :request do it "creates an article and get the response as json" do headers = { "ACCEPT" => "application/json" } post "/articles", :params => {:article => {:title => "test title", :text => "test text"}}, :headers => headers article_resp...
class Task < ActiveRecord::Base belongs_to :user validates :user_id, presence: true validates_presence_of :name end
require 'rails_helper' RSpec.describe BankServer do before(:all) { @bs = BankServer.new(FiatConfig.new["bank"], Logger.new(STDOUT)) } let!(:transfers_data) { create_list(:transfer_in, 10) } let(:transfer_id) { transfers_data.first.id } let(:deposit_remote) { {"deposit_id"=> "123", "l...
ActiveAdmin.register AssetOwnerHistory do controller do before_filter only: :index do @per_page = 10_000_000 if request.format == 'text/csv' end end actions :all, :except => [:destroy, :new, :edit] filter :asset filter :created_at filter :event, :as => :select, :collection => AssetOwnerHisto...
class Skill < ActiveRecord::Base belongs_to :people has_and_belongs_to_many :projects, :join_table => :projects_skills end
class AddAttachmentPhotoToVehicleImages < ActiveRecord::Migration def self.up change_table :vehicle_images do |t| t.attachment :photo t.integer :vehicle_id end end def self.down remove_attachment :vehicle_images, :photo end end
require "./lib/key_generator" require "pry" class Encrypt CHARACTER_MAP = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " ...