text
stringlengths
10
2.61M
# refs. http://qiita.com/yancya/items/1167e9764719151d0c80 # http://qiita.com/kasei-san/items/0392097791d3a5998216 class ZunDoko1 def initialize puts '' puts '##### ZunDoko1 #####' end def zundoko z, d = zd = ['ズン', 'ドコ'] w1, w2, w3, w4, w5 = 5.times.map { nil } until [w1, w2, w3, w4, w5] ==...
class CategorySerializer < ActiveModel::Serializer has_many :ingredients attributes :id, :name, :image, :ingredients end
class PaymentsController < ApplicationController def create @invoice = Invoice.find(params[:payment][:invoice_id]) payment_method = params[:payment][:payment_method] updated_params = payment_params.merge(:payment_method_id => Payment.set_payment_method_id(payment_method)).except("payment_method") @pay...
class AddIndexesToStudentAttachment < ActiveRecord::Migration def self.up add_index :student_attachments, :student_id, :name => "index_on_student_id" add_index :student_attachments, [:student_id, :is_registered], :name => "index_on_student_id_and_is_registered" add_index :student_attachment_records, :stud...
class GameController < ApplicationController before_action :set_current_game, only: [:shoot, :save, :show] def new @game = Game.new render json: @game end def shoot render json: @current_game.shoot(game_params) end def save render json: @current_game.save(game_params) end def show ...
class PledgesController < ApplicationController before_filter :load_project_and_funding_levels def new @pledge = Pledge.new end def create @pledge = Pledge.new(pledge_params.merge(:funding_level_id => find_appropriate_reward)) if @pledge.save flash[:notice] = "Your pledge was successfully created...
# Write a program that can find the sum of all the multiples of particular numbers, up to but not including a given number. # # If we list all the natural numbers up to but not including 20, that are multiples of either 3 or 5, we get: # 3, 5, 6, 9, 10, 12, 15, and 18. # The sum of these multiples is 78. # # Write...
class FixColumnInvoices1 < ActiveRecord::Migration def change remove_column :invoices, :datetime add_column :invoices, :emailed, :datetime end end
require_relative '../../converter/html' module Kramdown module Parser module Denden RUBY_START = /{([^}|]+)(?<!\\)\|([^}]+)}/ def parse_ruby ruby = Element.new(:ruby) rb = @src[1] rts = @src[2].split('|') @src.pos += (rb.bytesize + 2) # +2 for "{" and "|" if rb...
require 'blankslate' require 'rspec' describe BlankSlate do RSPEC_MOCK_METHODS = [ "as_null_object", "null_object?", "received_message?", "should", "should_not", "should_not_receive", "should_receive", "stub", "stub_chain", "unstub" ] let(:blank_slate) { BlankSlate.new }...
require 'net/http' require 'uri' namespace :print_redirect do desc 'リダイレクトの確認' task :run do def print_url(url) redirect_url = Net::HTTP.get_response(URI.parse(url))['location'] puts "#{url} => #{redirect_url}" end BASE_URL = 'http://localhost:3760/home' QUERY_STRING = '?foo=1&bar=2&baz...
# # Cookbook Name:: liferay # Attributes:: default # # Copyright 2015, Thirdwave, LLC # Authors: # Adam Krone <adam.krone@thirdwavellc.com> # Henry Kastler <henry.kastler@thirdwavellc.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t...
require "bitflyer_api/http/middleware" require "faraday" require "faraday_middleware" module BitflyerApi module HTTP class Connection extend Forwardable def_delegators :@conn, :get, :post def initialize(key, secret) @conn = Faraday.new(url: "https://api.bitflyer.jp") do |conn| ...
class Chef # Ruby module module Ruby # ScriptHelpers module module ScriptHelpers include Chef::Mixin::Command def exec_in_ruby_version(code, ruby_version, user = nil, chruby_install_path = node['ruby']['chruby']['install_path']) chruby_exec_string = "bash -c 'source #{chruby_install_pat...
require 'cucumber/core/ast/examples_table' module Cucumber::Core::Ast describe ExamplesTable do let(:location) { double(:to_s => 'file.feature:8') } describe ExamplesTable::Header do let(:header) { ExamplesTable::Header.new(%w{foo bar baz}, location) } describe 'location' do it 'knows t...
class PatientsController < ApplicationController def new @patient = Patient.new end def create @patient = Patient.new(patient_params) @patient.coach = current_coach if @patient.save redirect_to root_path, notice: "New patient created!" else render :new end end def show ...
class AddOwnerToInvites < ActiveRecord::Migration def change add_column :invites, :owner_id, :integer, :null => false add_index :invites, :owner_id end end
module Autoproj # Adds the relevant options to handle a gitorious server # What this does is ask the user how he would like to access the gitorious # server. Then, it sets # # #{name}_ROOT to be the base URL for pulling # #{name}_PUSH_ROOT to be the corresponding ssh-based URL for pushing ...
require "kryppiebot" require "listeners/thank_you" require "logging" module Listeners @default_listeners = [ ->(msg) { Logging.log(:info).message(msg.inspect) }, ->(msg) { ThankYou.new.listen(msg) } ].freeze def self.default_listeners @default_listeners end end
require 'test_helper' class VillainsControllerTest < ActionController::TestCase setup do @villain = villains(:one) @update = { :name => 'The Riddler', :gender => 'male', :image_url => 'images/riddler.jpg', :intel => 100, :str => 10, :speed => 12, :durab => 14, :power => 10, :combat => 14 } ...
class Line def initialize(p1, p2) @p1 = p1 @p2 = p2 end def to_s "(#{@x}, #{@y})" end end class Vector <Line def initialize(p1, p2, d) super(p1, p2) @d = d end end class Point attr_reader :x, :y def initialize(x,y) @x = x @y = y end def add(other_point) Point.new(@x + other_point.x, @y +other_...
# Write a method that takes one argument, a positive integer, and returns a string of alternating 1s and 0s, always starting with 1. The length of the string should match the given integer. def stringy(number) string = "" number.times do |i| number = i % 2 == 0 ? '1' : '0' string << number end string ...
module SequelSpec module Matchers module Association class HaveManyToOneMatcher < AssociationMatcher def association_type :many_to_one end end def have_many_to_one(*args) HaveManyToOneMatcher.new(*args) end end end end
#out own to_s def num_to_s(num, base=10) numbers_to_strings = Hash.new (0..9).each do |i| numbers_to_strings[i] = i.to_s end (10..15).each do |i| numbers_to_strings[i] = ('A'..'Z').to_a[i - 10] end divisor = 1 result = [] loop do break if (num / divisor) == 0 result.unshift( (num / di...
=begin problem: Find the longest substring in alphabetical order input: string output: string (longest substring in alphabetical order) explicit rules: 1. one string will be passed into method as an argument 2. The input will only consist of lowercase characters and will be at least one letter long. 3. if there a...
# -*- coding: utf-8 -*- require "./Gnuhead.rb" class ConnectAnotherServThread def initialize(sock) @sock = sock end # Methods def waitLoop # thread本体の処理 Thread.start() do while true disc = recvDisc() next if (myDisc?(disc)) # 自分が送ったものなら無視 next if (sameDisc?(d...
class UserSerializer < ActiveModel::Serializer attributes :id, :company, :name, :username, :role, :email, :birthdate, :gender, :created_at, :updated_at#, :picture_id belongs_to :picture has_one :block end
class CreateTransportFeeFinanceTransactions < ActiveRecord::Migration def self.up create_table :transport_fee_finance_transactions do |t| t.decimal :transaction_balance,:precision => 8, :scale => 2 t.decimal :transaction_amount,:precision => 8, :scale => 2 t.integer :finance_transaction_id ...
# frozen_string_literal: true module Knuckles # The `Pipeline` is used to transform a collection of objects into a # serialized result. A pipeline reduces a collection of objects through a set # of stages, passing the result of each stage on to the next. This means that # each stage can act in isolation and ca...
require "rails_helper" RSpec.describe Rook do describe "#valid_move?" do context "given a Rook at [0,0]" do let(:game) {Game.create} let(:rook) {Rook.create(position_x: 0, position_y: 0, game: game)} it "will return true when trying to move to [0,6]" do expect(rook.valid_move?(0,6)).to ...
module Slugifiable module InstanceMethods def slug #strip out any special characters, and replace all spaces with `-`. For a song, artist and genre self.name.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') end end #<#Artist>.slug module ClassMethods def find_by_slug(slug) #uses t...
require File.expand_path('../spec_helper', __FILE__) def print_table(result) table = Terminal::Table.new do |t| row = result.first heads = row["value"].map{ |k,v| k } t.headings = [ "_id", *heads] result.each do |row| id, value = row["_id"], row["value"] t.add_row [id , *(heads.map{ |k| ...
class Patient < ApplicationRecord validates_presence_of :name has_many :appointments, dependent: :destroy has_many :doctors, through: :appointments end
source 'https://rubygems.org' group :development do gem 'rake', '~> 10.3' gem 'pry' gem 'pry-byebug' gem 'pry-rescue', '~> 1.3' gem 'pry-stack_explorer', '~> 0.4' end group :test do gem 'foodcritic', '~> 4.0' gem 'chefspec', '~> 4.1' gem 'ci_reporter_rspec', '~> 1.0' gem 'test-kitchen', '~> 1.2' g...
require 'google_geocoder' require 'exceptions' class TripBuilder include Sidekiq::Worker sidekiq_options :queue => :trip_builder @@geocoder = GoogleGeocoder::GoogleGeocoder.new # trip fields # url # name # description # itinerary # place # name - also for geolocation lookup # ...
require 'rspec' class ChangeMachine def change(money) change_given = [] quarter_count = money / 25 money = money % 25 dime_count = money / 10 money = money % 10 nickel_count = money / 5 penny_count = money % 5 quarter_count.times do change_given << 25 end dime...
require 'javaclass/java_name' require 'javaclass/classlist/package_entry' module JavaClass module ClassList # Classes to form a list of JDK classes to find classes which have been # added in new releases. This is the list containing packages (PackageEntry). # Author:: Peter Kofler ...
Rails.application.routes.draw do namespace :api, as: '' do resources :users, only: [] do collection do # Authenticate post 'sign_in', to: 'users#sign_in' post 'auth/facebook', to: 'users#auth_facebook' post 'sign_up', to: 'users#sign_up' post 'sign_out', to: 'users#si...
cask :v1 => 'quiterss' do version '0.16.1' sha256 'b452fe75c3b825ae3074d4cc70ee29e18b445fb9a7cbccc2901b076bdfe41a07' url "http://quiterss.org/files/#{version}/QuiteRSS-#{version}.dmg" homepage 'http://quiterss.org/' license :unknown # todo: change license and remove this comment; ':unknown' is a machine-g...
class MultiVirtualProduct < VirtualProduct def type_name "多用户(#{self.person_amount})" end end
File.open(ARGV[0]).each_line do |line| numbers = line.strip.gsub(' ', '').chars.map(&:to_i) numbers.map!.with_index { |n, i| i % 2 == 0 ? n*2 : n } puts numbers.inject(0, :+) % 10 == 0 ? "Real" : "Fake" end
module GovukDesignSystem class Engine < ::Rails::Engine isolate_namespace GovukDesignSystem initializer "govuk_design_system.action_view" do |_app| ActiveSupport.on_load(:action_view) do # NOTE: These includes make the helpers available in every view of the # consuming application. If...
shared_context 'always' do end shared_context 'Testimonials Tab' do let(:initial_path){refinery.admin_root_path} end # shared_context 'Exisitng testimonial' do # let(:existing_testimonial) {FactoryGirl.build(:testimonial, name: 'Update me', quote: 'quote')} # let(:initial_path) {refinery.edit_testimonial_path(...
require 'fluent/config' module Fluent::Config::Expander def self.replace(str, mapping) mapping.reduce(str){|r, pair| r.gsub(pair[0], pair[1])} end def self.expand(element, mapping) name = replace(element.name, mapping) arg = replace(element.arg, mapping) attrs = element.reduce({}){|r, pair| r[re...
class Api::V1::TicketsController < ApplicationController def index tickets = Ticket.all options = { include: [:messages, :owner, :customer] } render json: TicketSerializer.new(tickets, options).serialized_json end def create ticket = Ticket.crea...
# ----------------------------------------- # Uncomment and set for use custom options. # ----------------------------------------- Rails.application.configure do # # Save DB Runtime?: Default: true # config.x.wprof.db_runtime = true # # Reporter Type (¿When we will save our data?): 'LOGGER' by default. # # Ano...
require 'encoding' # GradeEntryForm can represent a test, lab, exam, etc. # A grade entry form has many columns which represent the questions and their total # marks (i.e. GradeEntryItems) and many rows which represent students and their # marks on each question (i.e. GradeEntryStudents). class GradeEntryForm < Active...
class Feedback < ApplicationRecord belongs_to :user belongs_to :guest, :class_name => "User" def accept self.update(accepted_at:Time.now) end end
class AddAttachmentsPhotoToAssignment2 < ActiveRecord::Migration def self.up add_column :assignment2s, :photo_file_name, :string add_column :assignment2s, :photo_content_type, :string add_column :assignment2s, :photo_file_size, :integer add_column :assignment2s, :photo_updated_at, :datetime end d...
module Lolita module Configuration module Tab class Default < Lolita::Configuration::Tab::Base def initialize *args,&block super validate end private def set_default_fields warn("Default fields are not set for DefaultTab.") end ...
require 'feedjira' module Seek class FeedReader #Fetches the feed entries - aggregated and ordered, for a particular category #the category may be either :project_news or :community_news def self.fetch_entries_for category raise ArgumentError.new("Invalid category - should be either :project_news ...
class User class Profile < ApplicationRecord self.table_name = 'user_profiles' serialize :unread_notifications, Array belongs_to :user, class_name: 'User' after_initialize :init def valid_pin?(pin_code) if pin_code.to_i == pin && pin_sent_at > Time.now - 5.minutes self.is_verified =...
# frozen_string_literal: true require 'test_helper' module Vedeu class HelperTestClass include Vedeu::Helper end # HelperTestClass describe Helper do let(:described) { Vedeu::Helper } let(:included_described) { Vedeu::HelperTestClass } let(:included_instance) { included_described....
require 'rails_helper' RSpec.describe Comment, type: :model do before(:each) do @category = Category.create(name:"cat") @item = Item.create(institution: "inst", average: nil, category_id:@category.id) @comment = Comment.create(body: "comm", score: 1, item_id:@item.id) end context "belongs to" do it {sho...
namespace :db do namespace :pc do desc 'Updates counters from users, talks, events and schedules' task update_counters: :environment do batch_size = ENV.fetch('BATCH_SIZE', 50) query = User.with_relations.batch_size(batch_size).all count = query.count query.each_with_index do |user, ...
class CreateClassEnrollments < ActiveRecord::Migration[5.0] def change create_table :class_enrollments do |t| t.references :user_profile, foreign_key: true t.references :class_level, foreign_key: true t.integer :year t.timestamps end end end
# Add up all of the ages from the Munster family hash: ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 } # ages.values.sum sum = 0 ages.each_value do |ages| sum += ages end sum
require_relative "lib.rb" # Create a point for each input line points = File.read(ARGV[0]).split("\n") .map { |l| Point.new(*l.split(",").map(&:strip).map(&:to_i)) } # Find smallest rect rect = smallest_rect_for_points(points) # Find the closest point to every cell in the rect closest = {} each_cell(rect) do |le...
# 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' patch 'subscribe/:email', to: 'home.subscribe' end end end end
require 'spec_helper' describe ApplicationController do describe '.edit_brigade_json' do describe 'when a valid brigade project id is given' do bp_with_tags = FactoryBot.create(:brigade_project_with_tags, title: 'proj1') bp_without_tags = FactoryBot.create(:brigade_project, title: 'proj2') it...
class Exam < ActiveRecord::Base has_many :cells, :dependent => :destroy has_many :questions, :through => :cells has_many :test_sessions, :dependent => :destroy def self.create_from_cvs( exam_name, cvs_path ) exam = Exam.create!( :name => exam_name ) # questions File.readlines( cvs_path ).each_wi...
class CarOwner attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def owner_cars Car.all.select {|car| car.owner == self} end def mechanics owner_cars.map {|car| car.mechanic} end def self.avg_cars_per_owner num_cars_...
FactoryGirl.define do factory :step do program trait :day_1 do name 'Take Measurements' step_class 'Measurement' day 0 position 1 end trait :day_2 do name 'Power Punch' step_class 'Workout' day 1 position 2 end tr...
# == Schema Information # # Table name: brackets # # id :integer not null, primary key # tournament_id :integer # matchup_id :integer # bye :boolean default(FALSE) # bracket_type :string # winner_child :integer # loser_child ...
# Preview all emails at http://localhost:3000/rails/mailers/order_notifier class OrderNotifierPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/order_notifier/receiver def receiver OrderNotifier.receiver end # Preview this email at http://localhost:3000/rails/mail...
# This program is meant to read a "$maze" and return the $solution of the $maze (eg, what takes it from @ to %) # This reads any $maze into an array of arrays with each node and line separate. With this, # each node has a unique array index which can be used to map out all four directions. # Looks at each of the s...
FactoryGirl.define do factory :case_study_gallery_image do title 'Give Cat - The javascript bookmarklet' file = File.join(Rails.root, 'spec', 'support', 'files', 'test_cat.png') image { Rack::Test::UploadedFile.new(file) } case_study end end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/../../shared_examples/servers_examples' describe 'Fog::Bluebox::Servers' do it_should_behave_like "Servers" # flavor 1 = 256, image 3 = gentoo 2008.0 subject { @flavor_id = '94fd37a7-2606-47f7-84d5-9000deda52ae' # Blo...
class CreateClients < ActiveRecord::Migration def change create_table :clients do |t| t.integer :return_focus t.integer :risk_focus t.integer :tolerance t.boolean :outlook t.boolean :diversification_intent t.float :proportion_invested t.float :wealth_growth_rate t.f...
class Libfour < Package desc "Library Four" homepage "http://www.libfour.org" release version: '1.1.1', crystax_version: 1 release version: '2.2.2', crystax_version: 2 release version: '3.3.3', crystax_version: 3 release version: '4.4.4', crystax_version: 4 end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :email, :presence => true geocoded_by :l...
class UsersController < ApplicationController protect_from_forgery with: :exception before_filter :validate_user before_action :set_user, only: [:destroy, :update] def new @user = User.new end def index @users = User.where("level > '#{session[:level]}'") end def create @user = User.new(us...
class Tag < ActiveRecord::Base has_and_belongs_to_many :albums validates(:text, {:presence => true}) end
class Api::V1::UrlsController < ApplicationController def redirect @url = Url.find_by(key: key_param) if @url.present? @url.update_attribute(:clicked, @url.clicked + 1) redirect_to @url.source, status: :found else render_not_found end end def shorten url = Url.shorten(sourc...
require 'rails_helper' # Specs in this file have access to a helper object that includes # the StudentsHelper. For example: # describe StudentsHelper do describe "string concat" do it "concats two strings with spaces" do @student = Student.create(first_name: "Lisa", last_name: "Simpson") expect(@stu...
# (c) goodprogrammer.ru # Модель вопроса. class Question < ActiveRecord::Base belongs_to :user belongs_to :author, class_name: 'User', optional: true validates :user, :text, presence: true end
Vagrant.configure(2) do |config| config.vm.box_url = 'https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box' config.vm.box = 'trusty64' config.vm.hostname = 'made-trusty' config.vm.network 'forwarded_port', guest: 80, host: 8000 config.vm.network 'forwarded_por...
class AddAmountsToTransactions < ActiveRecord::Migration[5.1] def change add_column :transactions, :total_amount, :float add_column :transactions, :recieved_amount, :float end end
require 'uri' class SearchEngine def self.search_subtitle(base_url, query, page=1) unless query.nil? query = URI.escape(query) link = 'util/carrega_legendas_busca/termo:' + query if page != 1 link = link + '/page:' + page end document = WebsiteUtils.open_document(base_url+li...
require 'rails_helper' RSpec.describe UsersController, type: :controller do describe 'GET #index' do let(:users) { create_list(:user, 5, distance: 90000) } it "populates an array of all user's albums" do users get :index, distance: '100' expect(assigns(:users)).to match_array(users) en...
require 'factory_bot' FactoryBot.define do factory :user do sequence(:name) { |n| "dude#{n}" } sequence(:email) { |n| "user#{n}@example.com" } password { 'password' } password_confirmation { 'password' } color { 'FF0000' } end factory :lobby do sequence(:name) {|n| "Lobby #{n}"} end ...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). require 'csv' csv_options = { col_sep: ';', quote_char: '"', headers: :first_row } filepath = 'db/d...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def test0 render html: "If you're reading this, application#test0 was created & routed correctly" end =begin $ rails generate controller StaticPages home help $ rails destroy controller StaticPages home help Und...
class AddUserIdToStatuses < ActiveRecord::Migration def change change_table :statuses do |t| t.column :user_id, :integer end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class ChangeAnswerOptionsAnswerTemplateTableName < ActiveRecord::Migration # Yes, this migration isn't perfect best-practices, but it is needed since we have a trouble with Oracle and table names that are too long. # Because oracle can't handle table names as long as "answer_options_answer_templates" the first migr...
# rspec ./spec/models/item_spec.rb # frozen_string_literal: true require 'rails_helper' require 'cancan/matchers' RSpec.describe Item, type: :model do let!(:user) { create(:user) } let!(:admin) { create(:admin) } let!(:item1) { build(:item1, user_id: admin.id, cordinate_id: cordinate1.id) } let(:cordinate1) ...
class PetshopsController < ApplicationController before_action :set_petshop, only: [:show, :edit, :update, :destroy] # GET /petshops # GET /petshops.json def index @petshops = Petshop.all end # GET /petshops/1 # GET /petshops/1.json def show end # GET /petshops/new def new @petshop = Pe...
class FtpController < ApplicationController before_filter :authenticate_user! layout 'sidebar-collapsed', :only => [:index] respond_to :html, :js def index @ftps = current_user.ftps end def new @sites = current_user.sites.where.not(provider: 3) @ftp = Ftp.new end def create @ftps = c...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #validates :email, uniqueness: false def...
class EmptySquare def to_s " " end def empty? true end def king? false end def value 0 end end
require 'colorize' class Simon COLORS = %w(red blue green yellow).freeze DIFFICULTIES = ["hard", "medium", "easy"] HARD = 0.5 MEDIUM = 1 EASY = 2 TIME_BETWEEN_TURNS = 1.7 attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] ...
class WorkoutDetail < ApplicationRecord belongs_to :exercise belongs_to :user_previous_workout def max_rep_weight [rep_1_weight, rep_2_weight, rep_3_weight, rep_4_weight, rep_5_weight].delete_if(&:nil?).max.to_f end def avg_rep_weight reps = [rep_1_weight, rep_2_weight, rep_3_weight, rep_4_weight, r...
require_relative '../acceptance_helper' feature 'Siging out' do given(:user) { create(:user) } scenario "existing user exits the account" do sign_in(user) visit root_path click_on 'Выйти' expect(page).to have_content 'Выход из системы выполнен.' end end
class Contact < ActiveRecord::Base validates :firstname, presence: true validates :username, presence: true validates :phonenumber, presence: true # belongs_to :circle # default_scope { order(firstname: :asc)} end
class Api::MovieController < Api::ApiController AMOUNT_OF_SENTENCES = 5 def index category = Category.find(params[:id]) movies_ids = category.movies.map { |movie| movie.id } sentences = Sentence.in_movies(movies_ids).first(AMOUNT_OF_SENTENCES) quizzes = helpers.fill_with_answers(sentences, category...
class QueryGenerator def initialize(space) @space = space end def generate_queries(n) queries = [] (1..n).each do |i| queries << generate_query end queries end private def generate_query # Randomize starting point from space x = @space.point.x + Random.rand(0..@space.widt...
# Classes # Defining a Class in Ruby # You terminate a class by using the keyword end. class Customer end # Ruby provides four types of variables − # Local Variables − # Local variables are the variables that are defined in a method. # Local variables are not available outside the method. You will see more detail...
class Api::ContactsController < ApplicationController respond_to :json def index @contacts = Contact.all render json: @contacts end def update @contact = Contact.find(params[:id]) if @contact.update_attributes(contact_params) render json: @contact else render json: @contact...
class AddZeroDefaultsToUserForRetirement < ActiveRecord::Migration def change change_column_default :users, :std_retirement_xp_pool, 0 change_column_default :users, :leg_retirement_xp_pool, 0 end end