http://github.com/icalendar/icalendar
Documentação melhor ainda está por vir, mas enquanto isso, as mudanças necessárias para passar de 1.x para 2.0 são resumidas pela diferença necessária para atualizar o README
iCalendar é uma biblioteca Ruby para lidar com arquivos iCalendar no formato iCalendar definido por RFC-5545.
require 'icalendar'
# Create a calendar with an event (standard method)
cal = Icalendar :: Calendar . new
cal . event do | e |
e . dtstart = Icalendar :: Values :: Date . new ( '20050428' )
e . dtend = Icalendar :: Values :: Date . new ( '20050429' )
e . summary = "Meeting with the man."
e . description = "Have a long lunch meeting and decide nothing..."
e . ip_class = "PRIVATE"
end
cal . publish
event = Icalendar :: Event . new
event . dtstart = DateTime . civil ( 2006 , 6 , 23 , 8 , 30 )
event . summary = "A great event!"
cal . add_event ( event )
event2 = cal . event # This automatically adds the event to the calendar
event2 . dtstart = DateTime . civil ( 2006 , 6 , 24 , 8 , 30 )
event2 . summary = "Another great event!"
params = { "altrep" => "http://my.language.net" , "language" => "SPANISH" }
event = cal . event do | e |
e . dtstart = Icalendar :: Values :: Date . new ( '20050428' )
e . dtend = Icalendar :: Values :: Date . new ( '20050429' )
e . summary = Icalendar :: Values :: Text . new "This is a summary with params." , params
end
event . summary . ical_params #=> {'altrep' => 'http://my.language.net', 'language' => 'SPANISH'}
# or
event = cal . event do | e |
e . dtstart = Icalendar :: Values :: Date . new ( '20050428' )
e . dtend = Icalendar :: Values :: Date . new ( '20050429' )
e . summary = "This is a summary with params."
e . summary . ical_params = params
end
event . summary . ical_params #=> {'altrep' => 'http://my.language.net', 'language' => 'SPANISH'}
Às vezes não nos importamos se o início ou o fim de um evento são objetos Date
ou DateTime
. Para isso, podemos usar DateOrDateTime.new(value)
. Chamar .call
no DateOrDateTime
retornado retornará imediatamente o objeto Date
ou DateTime
subjacente.
event = cal . event do | e |
e . dtstart = Icalendar :: Values :: DateOrDateTime . new ( '20140924' )
e . dtend = Icalendar :: Values :: DateOrDateTime . new ( '20140925' ) . call
e . summary = 'This is an all-day event, because DateOrDateTime will return Dates'
end
Para clientes que podem analisar e exibir uma URL associada a um evento, é possível atribuir uma.
event = cal . event do | e |
e . url = 'https://example.com'
end
cal_string = cal.to_ical
puts cal_string
cal . event do | e |
# ...other event properties
e . alarm do | a |
a . action = "EMAIL"
a . description = "This is an event reminder" # email body (required)
a . summary = "Alarm notification" # email subject (required)
a . attendee = %w( mailto:[email protected] mailto:[email protected] ) # one or more email recipients (required)
a . append_attendee "mailto:[email protected]"
a . trigger = "-PT15M" # 15 minutes before
a . append_attach Icalendar :: Values :: Uri . new ( "ftp://host.com/novo-procs/felizano.exe" , "fmttype" => "application/binary" ) # email attachments (optional)
end
e . alarm do | a |
a . action = "DISPLAY" # This line isn't necessary, it's the default
a . summary = "Alarm notification"
a . trigger = "-P1DT0H0M0S" # 1 day before
end
e . alarm do | a |
a . action = "AUDIO"
a . trigger = "-PT15M"
a . append_attach "Basso"
end
end
# BEGIN:VALARM
# ACTION:EMAIL
# ATTACH;FMTTYPE=application/binary:ftp://host.com/novo-procs/felizano.exe
# TRIGGER:-PT15M
# SUMMARY:Alarm notification
# DESCRIPTION:This is an event reminder
# ATTENDEE:mailto:[email protected]
# ATTENDEE:mailto:[email protected]
# END:VALARM
#
# BEGIN:VALARM
# ACTION:DISPLAY
# TRIGGER:-P1DT0H0M0S
# SUMMARY:Alarm notification
# END:VALARM
#
# BEGIN:VALARM
# ACTION:AUDIO
# ATTACH;VALUE=URI:Basso
# TRIGGER:-PT15M
# END:VALARM
Chamar o método event.alarm
criará um alarme se não existir. Para verificar se um evento possui alarme utilize o has_alarm?
método.
event . has_alarm?
# => false
event . alarm
# => #<Icalendar::Alarm ... >
event . has_alarm?
#=> true
cal = Icalendar :: Calendar . new
cal . timezone do | t |
t . tzid = "America/Chicago"
t . daylight do | d |
d . tzoffsetfrom = "-0600"
d . tzoffsetto = "-0500"
d . tzname = "CDT"
d . dtstart = "19700308T020000"
d . rrule = "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
end
t . standard do | s |
s . tzoffsetfrom = "-0500"
s . tzoffsetto = "-0600"
s . tzname = "CST"
s . dtstart = "19701101T020000"
s . rrule = "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
end
end
# BEGIN:VTIMEZONE
# TZID:America/Chicago
# BEGIN:DAYLIGHT
# TZOFFSETFROM:-0600
# TZOFFSETTO:-0500
# TZNAME:CDT
# DTSTART:19700308T020000
# RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
# END:DAYLIGHT
# BEGIN:STANDARD
# TZOFFSETFROM:-0500
# TZOFFSETTO:-0600
# TZNAME:CST
# DTSTART:19701101T020000
# RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
# END:STANDARD
# END:VTIMEZONE
iCalendar tem suporte básico para a criação de blocos VTIMEZONE a partir de informações de fuso horário extraídas de tzinfo
. Você deve solicitar o suporte tzinfo
manualmente para aproveitar as vantagens.
iCalendar foi testado e funciona com as versões 0.3, 1.xe 2.x tzinfo
. A gema tzinfo-data
também pode ser necessária dependendo da sua versão do tzinfo
e, potencialmente, do seu sistema operacional.
require 'icalendar/tzinfo'
cal = Icalendar :: Calendar . new
event_start = DateTime . new 2008 , 12 , 29 , 8 , 0 , 0
event_end = DateTime . new 2008 , 12 , 29 , 11 , 0 , 0
tzid = "America/Chicago"
tz = TZInfo :: Timezone . get tzid
timezone = tz . ical_timezone event_start
cal . add_timezone timezone
cal . event do | e |
e . dtstart = Icalendar :: Values :: DateTime . new event_start , 'tzid' => tzid
e . dtend = Icalendar :: Values :: DateTime . new event_end , 'tzid' => tzid
e . summary = "Meeting with the man."
e . description = "Have a long lunch meeting and decide nothing..."
e . organizer = "mailto:[email protected]"
e . organizer = Icalendar :: Values :: CalAddress . new ( "mailto:[email protected]" , cn : 'John Smith' )
end
# Open a file or pass a string to the parser
cal_file = File . open ( "single_event.ics" )
# Parser returns an array of calendars because a single file
# can have multiple calendars.
cals = Icalendar :: Calendar . parse ( cal_file )
cal = cals . first
# Now you can access the cal object in just the same way I created it
event = cal . events . first
puts "start date-time: #{ event . dtstart } "
puts "start date-time timezone: #{ event . dtstart . ical_params [ 'tzid' ] } "
puts "summary: #{ event . summary } "
Você também pode criar uma instância Parser
diretamente, isso pode ser usado para permitir a análise estrita:
# Sometimes you want to strongly verify only rfc-approved properties are
# used
strict_parser = Icalendar :: Parser . new ( cal_file , true )
cal = strict_parser . parse
# Open a file or pass a string to the parser
event_file = File . open ( "event.ics" )
# Parser returns an array of events because a single file
# can have multiple events.
events = Icalendar :: Event . parse ( event_file )
event = events . first
puts "start date-time: #{ event . dtstart } "
puts "start date-time timezone: #{ event . dtstart . ical_params [ 'tzid' ] } "
puts "summary: #{ event . summary } "
Muitas vezes, em aplicativos da web e outros aplicativos interativos, você precisará pesquisar itens em um calendário para fazer alterações ou obter detalhes. Agora você pode encontrar tudo pelo ID exclusivo associado automaticamente a todos os componentes.
cal = Calendar . new
10 . times { cal . event } # Create 10 events with only default data.
some_event = cal . events [ 5 ] # Grab it from the array of events
# Use the uid as the key in your app
key = some_event . uid
# so later you can find it.
same_event = cal . find_event ( key )
Verifique os testes de unidade para obter exemplos da maioria das coisas que você deseja fazer, mas envie-me um exemplo de código ou deixe-me saber o que está faltando.
A versão mais recente desta biblioteca pode ser encontrada em
É tudo sobre rubis:
$ gem install icalendar
Para executar os testes:
$ bundle install
$ rake spec
Esta biblioteca é lançada sob a mesma licença do próprio Ruby.
Envie solicitações pull de uma ramificação de tópico reformulada e inclua testes para todos os bugs e recursos.
Como contribuidores e mantenedores deste projeto, nos comprometemos a respeitar todas as pessoas que contribuem através de relatórios de problemas, publicação de solicitações de recursos, atualização de documentação, envio de pull requests ou patches e outras atividades.
Estamos empenhados em tornar a participação neste projeto uma experiência livre de assédio para todos, independentemente do nível de experiência, género, identidade e expressão de género, orientação sexual, deficiência, aparência pessoal, tamanho corporal, raça, etnia, idade ou religião.
Exemplos de comportamento inaceitável por parte dos participantes incluem o uso de linguagem ou imagens sexuais, comentários depreciativos ou ataques pessoais, trollagem, assédio público ou privado, insultos ou outra conduta não profissional.
Os mantenedores do projeto têm o direito e a responsabilidade de remover, editar ou rejeitar comentários, commits, códigos, edições de wiki, problemas e outras contribuições que não estejam alinhadas com este Código de Conduta. Os mantenedores do projeto que não seguirem o Código de Conduta poderão ser removidos da equipe do projeto.
Este código de conduta aplica-se tanto nos espaços do projeto como nos espaços públicos quando um indivíduo representa o projeto ou a sua comunidade.
Instâncias de comportamento abusivo, de assédio ou de outra forma inaceitável podem ser relatadas abrindo um problema ou entrando em contato com um ou mais mantenedores do projeto.
Este Código de Conduta é adaptado do Contributor Covenant, versão 1.1.0, disponível em http://contributor-covenant.org/version/1/1/0/