root/trunk/plagger/lib/Plagger/Rule/FeedAttr.pm

Revision 78 (checked in by miyagawa, 3 years ago)
  • Reverted hooks method on rules.
  • Added rule_hook to Plugin, which is the only point where rule can control. Refs #22
Line 
1 package Plagger::Rule::FeedAttr;
2 use strict;
3 use base qw( Plagger::Rule );
4
5 use Plagger::Operator;
6 use Plagger::Feed;
7
8 sub init {
9     my $self = shift;
10
11     if (my $attrs = $self->{attrs}) {
12         $attrs = [ $attrs ] if ref($attrs) ne 'ARRAY';
13         $self->{attrs} = $attrs;
14     } else {
15         Plagger->context->error("Can't parse attr");
16     }
17    
18     my $feed = Plagger::Feed->new;
19     for my $attr (@{$self->{attrs}}) {
20         unless ($feed->can($attr->{name})) {
21             Plagger->context->error("Unsupported attr name '$attr->{name}'");
22         }
23        
24         if (my $value = $attr->{value}) {
25             $value = [ $value ] if ref($value) ne 'ARRAY';
26             $self->{value} = $value;
27         } else {
28             Plagger->context->error("Can't parse value in '$attr->{name}'");
29         }
30            
31         $attr->{op} ||= 'OR';
32         unless (Plagger::Operator->is_valid_op($attr->{op})) {
33             Plagger->context->error("Unsupported operator $self->{op} in '$attr->{name}'");
34         }
35     }
36
37     $self->{op} ||= 'OR';
38     unless (Plagger::Operator->is_valid_op($self->{op})) {
39         Plagger->context->error("Unsupported operator $self->{op}");
40     }
41 }
42
43 sub dispatch {
44     my($self, $args) = @_;
45
46     my $feed = $args->{feed}
47         or Plagger->context->error("No feed object in this plugin phase");
48
49     my @bool;
50     for my $attr (@{$self->{attrs}}) {
51         my @value;
52         my $name = $attr->{name};
53         for my $want (@{$attr->{value}}) {
54             if ($want =~ m{^/(.+?)/(i?)$}) {
55                 my ($pattern, $icase) = ($1, $2);
56                 if ($icase) {
57                     push @value, ($feed->$name() =~ m{$pattern}i);
58                 } else {
59                     push @value, ($feed->$name() =~ m{$pattern});
60                 }
61             } else {
62                 push @value, ($feed->$name() eq $want);
63             }
64         }
65         push @bool, Plagger::Operator->call($attr->{op}, @value);
66     }
67
68     Plagger::Operator->call($self->{op}, @bool);
69 }
70
71 1;
72 __END__
73 example config.
74     rule:
75       - module: FeedAttr
76         op: AND
77         attrs:
78           -
79             name: type
80             op: NOR
81             value:
82               - mixi
83               - frepa
84           -
85             name: link
86             op: OR
87             value:
88               - /Yappo/i
89               - /bulknews/
Note: See TracBrowser for help on using the browser.