Хэл Фултон - Программирование на языке Ruby
- Название:Программирование на языке Ruby
- Автор:
- Жанр:
- Издательство:ДМК Пресс
- Год:2007
- Город:Москва
- ISBN:5-94074-357-9
- Рейтинг:
- Избранное:Добавить в избранное
-
Отзывы:
-
Ваша оценка:
Хэл Фултон - Программирование на языке Ruby краткое содержание
Ruby — относительно новый объектно-ориентированный язык, разработанный Юкихиро Мацумото в 1995 году и позаимствовавший некоторые особенности у языков LISP, Smalltalk, Perl, CLU и других. Язык активно развивается и применяется в самых разных областях: от системного администрирования до разработки сложных динамических сайтов.
Книга является полноценным руководством по Ruby — ее можно использовать и как учебник, и как справочник, и как сборник ответов на вопросы типа «как сделать то или иное в Ruby». В ней приведено свыше 400 примеров, разбитых по различным аспектам программирования, и к которым автор дает обстоятельные комментарии.
Издание предназначено для программистов самого широкого круга и самой разной квалификации, желающих научиться качественно и профессионально работать на Ruby.
Программирование на языке Ruby - читать онлайн бесплатно ознакомительный отрывок
Интервал:
Закладка:
Предположим, что начало координат находится не в точке (0, 0)
, а в точке (50, 50)
. Тогда отрезок из точки (15, 20)
в точку (35, 40)
на самом деле будет соединять точки с координатами (65, 70)
и (85, 90)
. Но код рисования отрезка об этом ничего не знает.
После переноса оси (то есть сдвига начала координат) мы можем изменить масштаб вдоль оси. Чтобы получить четыре квадранта, следует уменьшить вдвое масштаб по осям X и Y ( pdf.scale_axis 0.5, 0.5
). Иными словами, если бы сейчас я провел отрезок между точками (0, 0)
и (90, 90)
, то без переноса осей он соединял бы точки с физическими координатами (0, 0)
и (45, 45)
, а с переносом — точки с координатами (90, 90)
и (135, 135)
. В любом случае будет проведена линия вдоль диагонали длиной 90 единиц измерения. Просто из-за масштабирования сами единицы стали в два раза меньше.
Затем мы отдаем управление блоку, а когда он закончит работу, восстанавливаем состояние, вызывая предоставленный библиотекой метод restore_state
. Иначе пришлось бы вручную увеличивать масштаб вдвое и переносить ось в обратном направлении.
15.4.2. Пример документа
Для демонстрации рассмотренной выше техники мы создадим четыре страницы в четырех разных квадрантах. Три из них — слегка измененные варианты демонстрационных программ, включённых в дистрибутив PDF::Writer
:
• demo.rb
, квадрант 1
• individual-i.rb
, квадрант 3
• gettysburg.rb
, квадрант 4
Четвертая страница (в квадранте 2) не имеет прямого аналога среди демонстрационных программ, она ближе всего к программе chunkybacon.rb
.
Весь код приведен в листинге 15.11, а результат показан на рис. 15.4. Пример довольно длинный, мы подробно обсудим его ниже.
require 'rubygems'
require 'pdf/writer'
def quadrant(pdf, quad)
raise unless block_given?
mx = pdf.absolute_x_middle
my = pdf.absolute_y_middle
pdf.save_state
case quad
when :ul
pdf.translate_axis 0, my
when :ur
pdf.translate_axis mx, my
when :ll
nil # no translation needed
when :lr
pdf.translate_axis mx, 0
end
pdf.scale_axis(0.5, 0.5)
pdf.у = pdf.page_height
yield
pdf.restore_state
end
pdf = PDF::Writer.new
pdf.select_font("Times-Roman",
rencoding => "WinAnsiEncoding",
differences => { 0x01 => "lozenge" })
mx = pdf.absolute_x_middle
my = pdf.absolute_y_middle
pdf.line(0, my, pdf.page_width, my).stroke
pdf.line(mx, 0, mx, pdf.page_height).stroke
# Левый верхний: Demo (UL).
quadrant(pdf, :ul) do
x = pdf.absolute_right_margin
r1 = 25
40.step(1, -3) do |xw|
tone = 1.0 - (xw / 40.0) * 0.2
pdf.stroke_style(PDF::Writer::StrokeStyle.new(xw))
pdf.stroke_color(Color::RGB.from_fraction(1, tone, tone))
pdf.line(x, pdf.bottom_margin, x,
pdf.absolute_top_margin).stroke
x -= xw+2
end
40.step(1, -3) do |xw|
tone = 1.0 - (xw / 40.0) * 0.2
pdf.stroke_style(PDF::Writer::StrokeStyle.new(xw))
pdf.stroke_color(Color::RGB.from_fraction(1, tone, tone))
pdf.circle_at(pdf.left_margin + 10, pdf.margin_height - 15,
r1).stroke
r1 += xw
end
pdf.stroke_color(Color::RGB::Black)
x = pdf.absolute_left_margin
y = pdf.absolute_bottom_margin
w = pdf.margin_width
h = pdf.margin_height
pdf.rectangle(x, y, w, h).stroke
text = "The Ruby Way"
y = pdf.absolute_top_margin
50.step(5, -5) do |size|
height = pdf.font_height(size)
y -= height
pdf.add_text(pdf.left_margin + 10, y, text, size)
end
(0...360).step(20) do |angle|
pdf.fill_color(Color::RGB.from_fraction(rand, rand, rand))
pdf.add_text(300 + Math.cos(PDF::Math.deg2rad(angle)) * 40,
300 + Math.sin(PDF::Math.deg2rad(angle)) * 40,
text, 20, angle)
end
end
pdf.fill_color Color::RGB::Black
# Правый верхний: Grampian Highlands (UR).
quadrant(pdf, :ur) do
pdf.image("grampian-highlands.jpg",
:height => pdf.margin_height,
:resize => :width)
pdf.text("The Grampian Highlands, Scotland",
justification => :center,
:font_size => 36)
pdf.text("\001August 2001\001", :justification => :center,
:font_size => 24)
pdf.move_pointer(24)
info = <<-'EOS'.split($/).join(" ").squeeze(" ")
This picture was taken during a driving vacation through the
Scottish highlands in August 2001 by Austin Ziegler.
EOS
pdf.text(info, :justification => :full, :font_size => 16,
:left => 100, :right => 100)
end
pdf.fill_color Color::RGB::Black
# Левый нижний: Individual-I (LL).
quadrant(pdf, :ll) do
require 'color/palette/monocontrast'
class IndividualI
def initialize(size = 100)
@size = size
end
# Размер буквы "i" в пунктах.
attr_accessor :size
def half_i(pdf)
pdf.move_to(0, 82)
pdf.line_to(0, 78)
pdf.line_to(9, 78)
pdf.line_to(9, 28)
pdf.line_to(0, 28)
pdf.line_to(0, 23)
pdf.line_to(18, 23)
pdf.line_to(18, 82)
pdf.fill
end
private :half_i
def draw(pdf, x, y)
pdf.save_state
pdf.translate_axis(x, y)
pdf.scale_axis(1 * (@size / 100.0), -1 * (@size / 100.0))
pdf.circle_at(20, 10, 7.5)
pdf.fill
half_i(pdf)
pdf.translate_axis(40, 0)
pdf.scale_axis(-1, 1)
half_i(pdf)
pdf.restore_state
end
end
ii = IndividualI.new(24)
x = pdf.absolute_left_margin
y = pdf.absolute_top_margin
bg = Color::RGB.from_fraction(rand, rand, rand)
fg = Color::RGB.from_fraction(rand, rand, rand)
pal = Color::Palette::MonoContrast.new(bg, fg)
sz = 24
(-5..5).each do |col|
pdf.fill_color pal.background[col]
ii.draw(pdf, x, y)
ii.size += sz
x += sz / 2.0
y -= sz / 2.0
pdf.fill_color
pal.foreground[col]
ii.draw(pdf, x, y)
x += sz / 2.0
y -= sz / 2.0
ii.size += sz
end
end
pdf.fill_color Color::RGB::Black
# Правый нижний: Gettysburg Address (LR).
# Это текст Геттисбергского обращения Авраама Линкольна.
quadrant(pdf, :lr) do
pdf.text("The Gettysburg Address\n\n",
:font_size => 36, justification => :center)
y0 = pdf.y + 18
speech = <<-'EOS'.split($/). join(" ").squeeze(" ")
Four score and seven years ago our fathers brought forth on
this continent a new nation, conceived in liberty and
dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether
that nation or any nation so conceived and so dedicated can
long endure. We are met on a great battlefield of that war.
We have come to dedicate a portion of that field as a final
resting-place for those who here gave their lives that that
nation might live. It is altogether fitting and proper that
we should do this. But in a larger sense, we cannot
dedicate, we cannot consecrate, we cannot hallow
this ground. The brave men, living and dead who struggled here
have consecrated it far above our poor power to add or
detract. The world will little note nor long remember what
we say here, but it can never forget what they did here. It
is for us the living rather to be dedicated here to the
unfinished work which they who fought here have thus far so
nobly advanced. It is rather for us to be here dedicated to
the great task remaining before us that from these honored
dead we take increased devotion to that cause for which they
gave the last full measure of devotion that we here highly
resolve that these dead shall not have died in vain, that
this nation under God shall have a new birth of freedom, and
that government of the people, by the people, for the people
Интервал:
Закладка: